阅读文本大概需要3分钟。
0x01:通过在Bean中定义init-method 和 destory-method方法
1. public class Car {
2.
3.
4. public Car() {
5. System.out.println("Car's Constructor..");
6. }
7.
8.
9. public void init(){
10. System.out.println("Car's Init...");
11. }
12.
13.
14. public void destory(){
15. System.out.println("Car's Destroy...");
16. }
17.
18.
19. }
20. @Bean(initMethod = "init",destroyMethod = "destory")
21. public Car car(){
22. return new Car();
23. }
0x02: 通过@PostConstruct和@PreDestroy方法实现初始化和销毁bean之前进行的操作
1. import javax.annotation.PostConstruct;
2. import javax.annotation.PreDestroy;
3.
4. @Service
5. public class CustomerService
6. {
7. String message;
8.
9.
10. public String getMessage() {
11. return message;
12. }
13.
14.
15. public void setMessage(String message) {
16. this.message = message;
17. }
18.
19.
20. @PostConstruct
21. public void initIt() throws Exception {
22. System.out.println("Init method after properties are set : " + message);
23. }
24.
25.
26. @PreDestroy
27. public void cleanUp() throws Exception {
28. System.out.println("Spring Container is destroy! Customer clean up");
29. }
30.
31. }
这两个注解是JDK自带的,因此与Spring的耦合性较低(必须要Spring扫描到这个java类才能执行使用该注解的方法)
0x03: 通过bean实现InitializingBean和DisposableBean接口
1. @Service
2. public class CustomeService implements InitializingBean, DisposableBean
3. {
4. String message;
5.
6.
7. public String getMessage() {
8. return message;
9. }
10.
11.
12. public void setMessage(String message) {
13. this.message = message;
14. }
15.
16.
17. public void afterPropertiesSet() throws Exception {
18. System.out.println("Init method after properties are set : " + message);
19. }
20.
21.
22. public void destroy() throws Exception {
23. System.out.println("Spring Container is destroy! Customer clean up");
24. }
25.
26. }
关注我
每天进步一点点