场景:
本人写的钉钉机器人组件出现空指针的bug,但是本地调试没有问题,
要通过SpringUtil的工具类获取到applicationtext,所以通过实现 ApplicationContextAware 来实现
但是实际使用中,并未使用
/**
* @author cocowwy.cn
* @create 2021-12-12-10:20
*/
@Configuration
@EnableConfigurationProperties({RobotsHookProperties.class, RobotsProperties.class})
public class DingtalkRobotAutoConfiguration {
@Bean
public DingTalkGroupApi dingTalkGroupApi() {
return new DingTalkGroupApi();
}
@Bean
public DingTalkRobotApi dingTalkRobotApi() {
return new DingTalkRobotApi();
}
@Bean
public SpringUtil spiringUtil(){
return new SpringUtil();
}
}
/**
* @author cocowwy.cn
* @create 2022-02-02-16:18
*/
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
解决:
在实际使用当中,因为使用了注解 @PostConstruct ,是在属性填充后执行,导致SpringUtil还未执行@Bean的时候,且setApplicationContext方法还未被执行,就已经在业务代码里被使用了