@PostConstruct和static静态块初始化的区别
@PostConstruct注解好多人以为是Spring提供的。其实是Java自己的注解。
static blocks are invoked when the class is being initialized, after it is loaded. The dependencies of your component haven't been initialized yet. That is why you get a NullPointerException (Your dependencies are null) .
Move your code to a method annotated with @PostConstruct. This will ensure that your code will run when all the dependencies of your component are initialized
译文:static模块会被引入,当class加载后。你的component组件的依赖还没有初始化。这就是为什么你的代码块会报空指针异常。(你的依赖都是null)
1,@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,
为此,可以使用@PostConstruct注解一个方法来完成初始化,
@PostConstruct注解的方法将会在依赖注入完成后被自动调用。
2,执行优先级高于非静态的初始化块,它会在类初始化(类加载的初始化阶段)的时候执行一次,执行完成便销毁,它仅能初始化类变量,即static修饰的数据成员。
初始化失败:
static {
strategyMap.put(SYSTEM, applicationContext.getBean(XXX.class));
System.out.println("初始化完成" + strategyMap.size());
}
初始化成功:
@PostConstruct
void init() {
strategyMap.put(SYSTEM, applicationContext.getBean(XXX.class));
System.out.println("初始化完成" + strategyMap.size());
);
}
@Async
在Spring中,基于@Async标注的方法,称之为异步方法;这些方法将在执行的时候,将会在独立的线程中被执行,调用者无需等待它的完成,即可继续其他的操作。
如何在Spring中启用@Async
基于Java配置的启用方式:
@Configuration @EnableAsync public class SpringAsyncConfig { ... }
基于XML配置文件的启用方式,配置如下:
1 <task:executor id="myexecutor" pool-size="5" /> 2 <task:annotation-driven executor="myexecutor"/>