Spring中如何对初始化和销毁bean之前进行相应操作呢?
下文笔者讲述Spring初始化和销毁bean之前操作的方法分享,如下所示
实现思路:
方式1:
使用@PostConstruct @PreDestroy注解 即可完成初始化和销毁前进行相应的操作
方式2:
使用xml定义init-method和destory-method方法,完成bean的初始化和销毁前操作
方式3:
使用bean实现InitializingBean和DisposableBean接口
使用@PostConstruct @PreDestroy注解实现初始化和销毁bean之前进行操作
@PostConstruct 和 @PreDestroy注解 并不是spring 而是JAVAEE的
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
bean定义
package com.java265.core.annotation.init;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class PersonService {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@PostConstruct
public void init(){
System.out.println("初始化方法 @PostConstrut...."+message);
}
@PreDestroy
public void dostory(){
System.out.println("销毁方法 @PreDestroy....."+message);
}
}
spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="personService" class="com.java265.core.annotation.init.PersonService">
<property name="java265" value="88888"></property>
</bean>
</beans>
测试类
package com.java265.core.annotation.init;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("resource/annotation.xml");
PersonService personService = (PersonService)context.getBean("personService");
personService.dostory();
}
}
------运行以上代码,将输出以下信息 初始化方法 @PostConstrut....88888 销毁方法 @PreDestroy.....88888
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


