项目中常会有这样的需求:
启动某web项目,当启动完成后,需要加载一下本地缓存。
此时,加一个 @PostConstruct 注解 搞定。
某次实践时,报空指针异常。这个类结构大概如下
推断可知,应该是spring的类加载顺序导致,class A 还没有注入b的示例,或者b的示例还在构建中。
修改如下
解决。
启动某web项目,当启动完成后,需要加载一下本地缓存。
此时,加一个 @PostConstruct 注解 搞定。
某次实践时,报空指针异常。这个类结构大概如下
@Component
class A{
@Autowire
B b;
@PostConstruct
public void init(){
//...
doSomething(b); //<-- 这里b为null
//...
}
}
推断可知,应该是spring的类加载顺序导致,class A 还没有注入b的示例,或者b的示例还在构建中。
修改如下
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
@Component
public class A implements ApplicationListener<ContextRefreshedEvent> {
private AtomicInteger initCount = new AtomicInteger(0);
@Autowire
B b;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法
//原子类保证只会加载一次
if (1 == initCount.incrementAndGet()) {
doSomething(b);
}
}
}
解决。