Spring(七):Bean 的初始化和销毁(注解实现)

  Spring Bean在使用之前或使用之后需要做一些操作,Spring对Bean的生命周期的操作提供了支持。

配置

  1. Java配置方式
    使用@BeaninitMethoddestroyMethod。相当于XML配置的init-methoddestory-method
  2. 注解方式
    利用JSR-250@PostConstruct@PreDestroy
    **@PostConstruct:**在构造函数执行完后执行。
    @PreDestroy:Bean销毁之前执行。

示例

  1. 导包js4250-api.jar
  2. 使用@Bean形式的Bean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.bean.initAndDestroy;

/**
* 使用@Bean形式的Bean
* @author Rocky
*
*/

public class BeanWayService {

public void init() {
System.out.println("@Bean-init-method");
}

public BeanWayService() {
super();
System.out.println("初始化构造函数-BeanWayService");
}

public void destroy() {
System.out.println("@Bean-destroy-method");
}
}
  1. 使用 JSR250 形式的Bean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.bean.initAndDestroy;

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


/**
* 使用JSR250形式的Bean
* @author Rocky
*
*/
public class JSR250WayService {

@PostConstruct
public void init() {
System.out.println("jsr250-init-method");
}

public JSR250WayService() {
super();
System.out.println("初始化构造函数-JSR250WayService");
}

@PreDestroy
public void destory() {
System.out.println("jsr250-destroy-method");
}
}
  1. 配置类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.bean.initAndDestroy;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.bean.initAndDestroy")
public class PrePostConfig {

@Bean(initMethod="init", destroyMethod="destroy")
BeanWayService beanWayService() {
return new BeanWayService();
}

@Bean
JSR250WayService jsr250WayService() {
return new JSR250WayService();
}
}
  1. 执行Main类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.bean.initAndDestroy;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainPrePost {

@SuppressWarnings("unused")
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(PrePostConfig.class);
BeanWayService beanWayService = context.getBean(BeanWayService.class);
JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);

context.close();
}
}
  1. 结果
1
2
3
4
5
6
初始化构造函数-BeanWayService
@Bean-init-method
初始化构造函数-JSR250WayService
jsr250-init-method
jsr250-destroy-method
@Bean-destroy-method

Spring(七):Bean 的初始化和销毁(注解实现)

http://blog.gxitsky.com/2018/03/18/Spring-07-bean-annotation-init-destroy/

作者

光星

发布于

2018-03-18

更新于

2022-06-17

许可协议

评论