@PostConstruct和@PreDestroy注解

这里写目录标题

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被彻底卸载之前。执行顺序流程如下:

服务器加载Servlet
Servlet构造函数
PostConstruct注解标识方法
init方法
Service
destroy销毁方法
ProDestroy注解标识方法
Servlet卸载

另外,spring中Constructor、DI(依赖注入)、@PostConstruct的顺序:

    根据依赖注入的业务逻辑,如果要将对象A注入到对象B中,那么就必须先生成对象A和对象B,执行Constructor。所以如果一个类B中有个对象属性需要被注入,那么依赖注入是发生在B的构造函数执行之后的。如果想在生成对象时完成一些初始化操作,并且这些初始化操作又依赖于DI(依赖注入),那么就需要通过@PostConstruct注解一个无参方法来完成该操作,@PostConstruct注解的方法将会在DI完成后背自动调用。执行顺序如下:

Constructor
DI-依赖注入
PostConstruct注解标识方法
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被彻底卸载之前。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值