加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Spring XML中applicationcontext的“this”引用

发布时间:2020-12-15 02:28:49 所属栏目:Java 来源:网络整理
导读:有没有办法在 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/s
有没有办法在 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属性之后发生.

Invoked after population of normal bean properties but before an init
callback such as InitializingBean.afterPropertiesSet() or a custom
init-method. Invoked after
ResourceLoaderAware.setResourceLoader(org.springframework.core.io.ResourceLoader),
ApplicationEventPublisherAware.setApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher)
and MessageSourceAware,if applicable.

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读