PostContruct/PreDestory功能描述
@PostConstruct用以标注方法,表示方法将在对象构建成功之后,被调用。
@PreDestory 用以标注方法, 表示方法将在对象被销毁之前,被调用。
应用场景
@PostContruct: 主要用来在初始化操作,例如加载配置文件,初始化连接等
@PreDestory: 主要用来在释放资源,比如,释放资源,释放链接,清空内存使用等
依赖类
在spring中,这些标注并未包含在内,他们是在javax.annotation-api的包中定义的,需要单独引用,在spring-boot则无需单独引用。
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
Alternative替代方案
如果很执着,不像单独引用新类库,只想使用Spring,则可以考虑如下技术方案:
public class MyBean implements InitializingBean, DisposableBean {
private void init() {
//TODO: init code
}
private void shutdown() {
//TODO: destroy code
}
@Override
public void afterPropertiesSet() throws Exception {
init();
}
@Override
public void destroy() throws Exception {
shutdown();
}
}
这两个接口分别会在创建对象和销毁对象之时触发。
注意事项
在使用这两个好用的注解之时,还需要在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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:annotation-config></context:annotation-config>
</beans>
设置spring使用注解来配置spring
@Bean的属性设置
@Bean主要用来在类内部声明和创建Bean实例。对于@Bean注解,其中可以定义的属性如下:
- initMethod, default ‘’
- destroyMethod, default ‘’
其作用等价于@PreDestroy和@PostConstruct的功能与用法。
使用示例:
@Configuration
@Slf4j
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "clearup")
public Game game() {
return new Game();
}
}
Game类的定义如下:
@Slf4j
public class Game {
public void init() {
log.info("init in the game");
}
public void clearup(){
log.info("clear up the demo");
}
}