java – Spring XML中applicationcontext的“this”引用
有没有办法在
Spring中的bean配置文件中引用当前的应用程序上下文?
我想做这样的事情: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <bean id="some-bean-name" class="com.company.SomeClass"> <constructor-arg> <!-- obviously this isn't right --> <bean ref=#{this}/> </constructor-arg> </bean> 问题是SomeClass在其构造函数中需要一个ApplicationContext实例.有没有办法获得正在加载bean的ApplicationContext的引用?我知道我可以在XML中完成所有的加载,但这不是我想要的,因为我需要在我的java代码中进行bean加载. 解决方法
你看过实施
ApplicationContextAware 吗?它不会在构造函数中出现,但它确实在init()调用之前发生,并且将在填充bean属性之后发生.
public class SomeClass implements ApplicationContextAware { //your class definition private ApplicationContext myContext; public void setApplicationContext(ApplicationContext context) throws BeansException { myContext = context; //load beans here maybe? } } 如果使用Spring 2.5或更高版本,你也可以@Autowire(d)它. public class SomeClass { //your class definition @Autowired private ApplicationContext myContext; } 当然,执行其中任何一项都会将代码绑定到Spring. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |