获取Spring容器Bean工具类
1、创建SpringUtils工具类
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
/**
* 根据类获取Bean
* @param clazz 例如 String.class
*/
public static <T> T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
}
2、注册 SpringUtils工具类
这一步是显示注册SpringUtils
工具类,其实可以使用 @Component
注解标注在 SpringUtils
类上面也可以,但是有些SpringBoot或者Spring版本当中注入 ApplicationContext 会为空,因为 ApplicationContext 是static变量,存在启动顺序上的问题,导致SpringUtils加载的时候,Spring容器还没有启动,所以无法注入进去
可以先试试 @Component
注解,如果有效,则不需要这一步
在 resource
目录下创建 spring
文件夹,创建 application-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="SpringUtils" class=" com.demo.utils.SpringUtils" lazy-init="false" />
</beans>
在启动类上加上注解@ImportResource(locations = {"classpath:spring/application-spring.xml"})
引入
并且加上 @DependsOn(value = "BeanUtil")
改变顺序优先级最高,因为会出现 有的 @Compoent类需要用到BeanUtils,但是ApplicationContext并还没有加载,导致 空指针异常,使用这个注解可以让BeanUtil优先级在顶级
@SpringBootApplication
@ImportResource(locations = {"classpath:spring/application-spring.xml"})
@DependsOn(value = "BeanUtil")
public class Application {
public static void main( String[] args ) {
SpringApplication.run(Application.class, args);
}
}
3、如果打包的是War方式,可能上面两个注册工具类的方法都没用
打包war有些地方会不一样,请参考其他打包war获取springBean工具类的相关博客