0

由于另一个库的要求,我必须ApplicationContext在我的 main 中定义ApplicationContext一个名称为default.context

<?xml version="1.0"?>
<beans>
    <bean name="default.context" class="org.springframework.context.support.ClassPathXmlApplicationContext">
        <constructor-arg>
            <list>
                <value>../other-file.xml
            </list>
        </constructor-arg>
    </bean>

    <bean class="MyNiceDependency"/>
</beans>

我怎样才能使上下文MyNiceDependency可用?default.context我假设我需要使用的parent属性,ClassPathXmlApplicationContext但如何将当前上下文注入它?

4

1 回答 1

1

这是应该完成工作的事情:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ThisApplicationContextFactoryBean implements FactoryBean<ApplicationContext>,
        ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;
    }

    public ApplicationContext getApplicationContext() {
        return this.applicationContext;
    }

    @Override
    public ApplicationContext getObject() throws Exception {
        return getApplicationContext();
    }

    @Override
    public Class<?> getObjectType() {
        return ApplicationContext.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

也许有更好的东西,或者更好的东西,包含在 Spring 中?

于 2012-08-06T21:44:15.550 回答