ApplicationContextAware-实现抽象类中注入对象

11 篇文章 0 订阅
6 篇文章 1 订阅

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
	}
}

正如前面所提,这并不是一种明智的做法,除非已到绝境,否则应该考虑其他方法实现

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值