手动注入Spring容器管理的对象
代码实现
Application(启动类Springboot)
SpringApplication springApplication = new SpringApplication(Application.class);
ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
GetBeanUtil.setApplicationContext(configurableApplicationContext);
GetBeanUtil
@Component
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.service"})//扫描包
public class GetBeanUtil {
private static ApplicationContext applicationContext;
/**
* 给applicationContext赋值
*/
public static void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
if(GetBeanUtil.applicationContext==null) {
GetBeanUtil.applicationContext=applicationContext;
}
}
/**
* 获取applicationContext
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过name 获取bean
* @param name
* @return
*/
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
/**
* 根据class获取bean
* @param <T>
* @param requiredType
* @return
*/
public static <T> T getBean(Class<T> requiredType) {
return getApplicationContext().getBean(requiredType);
}
/**
* 根据name以及class返回指定bean
* @param <T>
* @param name
* @param requiredType
* @return
*/
public static <T> T getBean(String name,Class<T> requiredType) {
return getApplicationContext().getBean(name, requiredType);
}
}
使用
private TestService testService;
public TestService getTestService() {
if (testService== null) {
testService= GetBeanUtil.getApplicationContext().getBean(TestService .class);
}
return testService;
}