Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:
Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; /** * @ClassName RedisUtil * @Description TODO * @Auther bingfeng * @Date 2019/7/4/004 17:14 * @Version 1.0 */ @Component public class RedisUtil { private static RedisTemplate<Object, Object> redisTemplates; @Autowired private RedisTemplate<Object, Object> redisTemplate; @PostConstruct public void initialize() { redisTemplates = this.redisTemplate; } /** * 添加元素 * * @param key * @param value */ public static void set(Object key, Object value) { if (key == null || value == null) { return; } redisTemplates.opsForValue().set(key, value); } }
@PostConstruct 在注入属性之后执行。
initmethod配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="person" class="com.nrsc.springstudy.c071_InitializingBean_initMethod_PostConstruct.beans.Cat" init-method="init"> <property name="name" value="花花"></property> </bean> </beans>
package com.nrsc.springstudy.c071_InitializingBean_initMethod_PostConstruct.beans; import org.springframework.beans.factory.InitializingBean; import javax.annotation.PostConstruct; /** * Created By: Sun Chuan * Created Date: 2019/7/7 22:19 */ public class Cat implements InitializingBean { private String name; //构造方法-----创建对象时调用 public Cat() { System.out.println("Cat......constructor............"); } //设置name属性时会调用 public void setName(String name) { System.out.println("===cat=========setName========"); this.name = name; } public String getName() { return name; } //在配置类中利用注解将initMethod指向下面的init方法----对应于initMethod的用法 public void init() { System.out.println("Cat......init............"); } //继承了InitializingBean接口,需要实现afterPropertiesSet方法---对应于InitializingBean的用法 public void afterPropertiesSet() throws Exception { System.out.println("Cat......afterPropertiesSet............"); } @PostConstruct public void init2(){ System.out.println("Cat......@PostConstruct............"); } }
@PostConstruct、InitialzingBean和initMethod 的功能相似。
spring初始化bean