这里写目录标题
Java EE5引入了@PostConstruct和@ProDestory两个作用于Servlet生命周期的注解,实现Bean初始化之前和销毁之前的自定义操作。
@PostConstruct
应用 PostConstruct 注释的方法必须遵守以下所有标准:
- 只有一个方法可以使用此注释进行注解;
- 被注解方法需是非静态方法;
- 被注解方法返回值为void;
- 被注解方法不得有任何参数;
- 被注解方法不得抛出已检查异常;
- 此方法只会被执行一次;
使用@PostConstruct写法有两种方式:
@PostConstruct
public void setProperties() {
....
}
public @PostConstruct void setProperties() {
....
}
被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。@PostConstruct在构造函数之后执行,init()方法之前执行,@ProDestroy方法在destory方法执行之后执行,在Servlet被彻底卸载之前。执行顺序流程如下:
另外,spring中Constructor、DI(依赖注入)、@PostConstruct的顺序:
根据依赖注入的业务逻辑,如果要将对象A注入到对象B中,那么就必须先生成对象A和对象B,执行Constructor。所以如果一个类B中有个对象属性需要被注入,那么依赖注入是发生在B的构造函数执行之后的。如果想在生成对象时完成一些初始化操作,并且这些初始化操作又依赖于DI(依赖注入),那么就需要通过@PostConstruct注解一个无参方法来完成该操作,@PostConstruct注解的方法将会在DI完成后背自动调用。执行顺序如下:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Objects;
/**
* redis配置文件类
*/
@Component
public class RedisProperties {
// 集群节点ip:port(多个以逗号隔开)
public static String hostPorts;
// 密码
public static String password;
// 最大连接数
public static Integer maxTotal;
// 最大空闲连接数
public static Integer maxIdle;
// 最小空闲连接数
public static Integer minIdle;
// 最大等待时间
public static Integer maxWaitMillis;
// 集群节点ip:port(多个以逗号隔开)
@Value("${redis.host-ports}")
private String host_ports;
// 密码
@Value("${redis.password}")
private String pwd;
// 最大连接数
@Value("${redis.jedis-pool-config.max-total}")
private Integer max_total;
// 最大空闲连接数
@Value("${redis.jedis-pool-config.max-idle}")
private Integer max_idle;
// 最小空闲连接数
@Value("${redis.jedis-pool-config.min-idle}")
private Integer min_idle;
// 最大等待时间
@Value("${redis.jedis-pool-config.max-wait-millis}")
private Integer max_wait_millis;
@PostConstruct
public void setProperties() {
hostPorts = this.host_ports;
password = this.pwd;
maxTotal = this.max_total;
maxIdle = this.max_idle;
minIdle = this.min_idle;
maxWaitMillis = this.max_wait_millis;
}
}
上面代码执行顺序为:先执行 RedisProperties 类的无参构造方法,然后执行@Value注解进行参数注入,最后执行@PostConstrust标注的方法setProperties()进行类属性赋值。
@PreDestroy
被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。