ApplicationContextAware-实现抽象类中注入对象
一、先上场景
父类
public abstract class BaseBusiness{
@Value("$test.value")
protected String value;
@Autowired
protected TestService testService;
@Resource
protected TestDao testDao;
}
子类
@Component
public class Test extends BaseBusiness{
pubilc void test(){
String value = this.value;
TestService testService = this.testService;
TestDao testDao = this.testDao
}
}
这代码看似没毛病,但实际上啥都不是
由于类加载顺序的问题,实例化子类时,会先实例化父类,那么再实例化父类时,其他资源都还没被加载,TestService、TestDao、注入时,也不会被找到。所以得到的结果就是,一切为虚空。
为了解决这种场景原本的需求,其实也有很多种方法,这里用的是实现ApplicationContextAware来引用上下文进行方法注入(每次获取将得到一个新的对象实例)。
二、简述
当ApplicationContext创建一个实现了org.springframework.context.ApplicationContextAware接口的对象实例时,该实例被提供了一个对该ApplicationContext的引用。因此,bean可以通过ApplicationContext接口或将引用转换为该接口的已知子类(例如ConfigurableApplicationContext,它公开了额外的功能),以编程方式操作创建它们的ApplicationContext。其中一个用途是对其他bean进行编程检索。
但是,一般情况下应该避免使用它,因为它将代码与Spring耦合在一起,而不遵循控制反转(Inversion of Control)风格。
三、实现
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static Object getObject(String id) {
Object object = null;
object = applicationContext.getBean(id);
return object;
}
public static ApplicationContext getSpringContext() {
return applicationContext;
}
}
父类
public abstract class BaseBusiness{
protected Environment env;
protected TestService testService;
protected TestDao testDao;
public BaseBusiness(){
this.env = (Environment) ApplicationContextUtil.getObject("environment");
this.testService = (TestService) ApplicationContextUtil.getObject("testService");
this.testDao = (TestDao) ApplicationContextUtil.getObject("testDao");
}
}
子类
@Component
public class Test extends BaseBusiness{
pubilc void test(){
String value = this.env.getProperty("test.value");;
TestService testService = this.testService;
TestDao testDao = this.testDao
}
}
正如前面所提,这并不是一种明智的做法,除非已到绝境,否则应该考虑其他方法实现