06点睛Spring4.1-Bean的初始化和销毁

阅读更多

6.1 Initialization和Destruction

  • spring对bean初始化的时候和销毁时候进行某些操作提供了支持
    • 利用@Bean的initMethoddestroyMethod(和xml配置的init-method和destory-method相同)
    • 利用JSR-250的@PostConstruct@PreDestroy

6.2 示例

6.2.1 @Bean形式的Initialization和Destruction

6.2.1.1 新建服务java类

package com.wisely.prepost;

public class BeanWayService {
    public void init(){
        System.out.println("init-method-bean");
    }
    public BeanWayService() {
        super();
        System.out.println("初始化构造函数-bean");
    }
    public void destroy(){
        System.out.println("destory-method-bean");
    }

}

6.2.1.2 新建配置java类

package com.wisely.prepost;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanWayConfig {
    @Bean(initMethod="init",destroyMethod="destroy")
    public BeanWayService beanWayService(){
        return new BeanWayService();
    }
}

测试

package com.wisely.prepost;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext("com.wisely.prepost");
        context.close();

    }

}

输出结果

初始化构造函数-bean
init-method-bean
destory-method-bean

6.2.2 JSR-250形式的Initialization和Destruction

6.2.2.1 添加jsr250-api到maven依赖

添加如下到pom.xml

<dependency>
    <groupId>javax.annotationgroupId>
    <artifactId>jsr250-apiartifactId>
    <version>1.0version>
dependency>

6.2.2.2 添加jsr250形式的服务类

package com.wisely.prepost;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.stereotype.Service;

@Service
public class JSR250WayService {
    @PostConstruct
    public void init(){
        System.out.println("init-method-annotation");
    }
    public JSR250WayService() {
        super();
        System.out.println("初始化构造函数-annotation");
    }
    @PreDestroy
    public void destroy(){
        System.out.println("destory-method-annotation");
    }
}

6.2.2.3 测试

package com.wisely.prepost;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =  new AnnotationConfigApplicationContext("com.wisely.prepost");
        context.close();

    }

}

输出结果

初始化构造函数-annotation
init-method-annotation
destory-method-annotation

新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。

 

京东地址:http://item.jd.com/11894632.html

当当地址:http://product.dangdang.com/23926195.html

亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6 

淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail

 

 

 

或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。

 


06点睛Spring4.1-Bean的初始化和销毁_第1张图片

你可能感兴趣的:(06点睛Spring4.1-Bean的初始化和销毁)