@PostConstruct注解
@PostConstruct注解好多人以为是Spring提供的。其实是Java自己的注解。
Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:
Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
Why use @PostConstruct?
because when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct
method the bean is fully initialized and you can use the dependencies.
because this is the contract that guarantees that this method will be invoked only once in the bean lifecycle. It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct
will be invoked only once.
@Configuration public class BeanConfiguration { @Bean public ToyFactory toyFactory() { return new DefaultToyFactory(); } }
接口
public interface ToyFactory { Toy createToy(); }
接口实现类
package com.sixinshuier.Initialization.servive.impl; import com.sixinshuier.Initialization.entity.Toy; import com.sixinshuier.Initialization.servive.ToyFactory; import javax.annotation.PostConstruct; public class DefaultToyFactory implements ToyFactory { public DefaultToyFactory() { System.out.println("构造器..."); } // 1. 基于 @PostConstruct 注解 @PostConstruct public void init() { System.out.println("@PostConstruct : DefaultToyFactory 初始化中..."); } @Override public Toy createToy() { Toy toy = new Toy(); toy.setName("Football"); toy.setSize("big"); return toy; } }
main
package com.sixinshuier.Initialization.main; import com.sixinshuier.Initialization.config.BeanConfiguration; import com.sixinshuier.Initialization.entity.Toy; import com.sixinshuier.Initialization.servive.ToyFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class PostConstructTest { public static void main(String[] args) { // 创建BeanFactory AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); // 注册Configuration Class(配置类) applicationContext.register(BeanConfiguration.class); // 启动spring应用上下文 applicationContext.refresh(); // 依赖查找 ToyFactory toyFactory = applicationContext.getBean(ToyFactory.class); Toy toy = toyFactory.createToy(); System.out.println("ToyName:" + toy.getName() + " ToySize:" + toy.getSize()); //关闭Spring应用上下文 applicationContext.close(); } }
输出结果
构造器...
@PostConstruct : DefaultToyFactory 初始化中...
ToyName:Football ToySize:big
参考:https://blog.csdn.net/qq360694660/article/details/82877222