学习使用spring boot 手动获取bean值的问题
1.测试类
@SpringBootApplication public class BootDemoApplication { public static void main(String[] args) { // ApplicationContext context = SpringApplication.run(BootDemoApplication.class, args); // MessageSender messageSender =(MessageSender)context.getBean(MessageSender.class); // System.out.println("MessageSender===="+messageSender); SpringApplication.run(BootDemoApplication.class, args); ApplicationContext con= SpringUtil.getApplicationContext(); MessageSender messageSender =(MessageSender)con.getBean(MessageSender.class); System.out.println("MessageSender===="+messageSender); messageSender.send(); }
2.写个工具类
@Component public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(applicationContext==null) { this.applicationContext= applicationContext; } } public static ApplicationContext getApplicationContext(){ return applicationContext; } public static Object getBean(String name){ return applicationContext.getBean(name); } //通过class获取Bean. public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } } 注意:看着网上写了个这个示例。调试发现怎么都获取不到ApplicationContext ,调试半天也没发现那里有问题。
最后发现是因为
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(applicationContext==null) { this.applicationContext= applicationContext; } }
这段代码中的参数变量不能和静态变量名相同。导致获取为null。你们是这样吗?