如何使用Annotations覆盖xml中定义的spring bean?

Wil*_*ill 7 spring spring-annotations

我有一个已overrideBean定义的bean spring.xml,我想用注释覆盖它.我尝试了以下来覆盖bean:

@Configuration
@ImportResource({"/spring.xml"})
public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DdwMain.class);

        Object o = context.getBean("overrideBean");
        // o should be null but it is not
    }

    @Bean(name="overrideBean")
    public OverrideBean overrideBean() {
        return null;
    }

}
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,spring.xml配置中的bean 始终被实例化并由context.getBean调用返回.

可以通过包含另一个XML配置文件来覆盖bean,@ImportResource但是我希望找到一个使用注释的解决方案更干净.

Tod*_*lev 6

通常 xml 注册的 bean 具有优先权。因此,您可以使用 xml 配置的 bean 覆盖带注释的 bean,但您正尝试以相反的方式进行操作。不能使用不同的bean名称并通过使用@Qualifier注释在多个候选者中选择它吗?

大多数时候,将 xml 与自动扫描结合起来很容易出错。


Cho*_*meh 5

我正在通过xml配置的较旧的应用程序(春季3.1.1)中工作,但我需要重新整理一些配置以进行测试,而又不会偏离生产配置太多。我的方法是使用BeanPostProcessor。

package myapp.test;

import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import myapp.spring.config.ComplexSpringConfiguration;

/**
 * Closely resembles production configuration for testing
 * @author jim
 */
@Configuration
@ImportResource("file:src/main/webapp/WEB-INF/spring-servlet.xml")
@Import(ComplexSpringConfiguration.class)
public class TestConfig {
    final Logger logger = LoggerFactory.getLogger(getClass());

    static {
        System.setProperty("env.test", "system");
    }

    //Override templateLoaderPath with something amenable to testing
    @Bean
    public BeanPostProcessor beanPostProcessor(){
        return new BeanPostProcessor(){
            @Override
            public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException  {
                //Override templateLoaderPath with something amenable to testing
                if(beanName.equals("freemarkerConfig")) {
                    logger.debug("overriding bean with name:" + beanName);
                    FreeMarkerConfigurer fc = new FreeMarkerConfigurer();
                    fc.setTemplateLoaderPath("file:src/main/webapp/WEB-INF/freemarker");
                    bean = fc;
                }
                return bean;
            }

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                return bean;
           }  
       };
    }

    @Bean
    public ServletContext servletContext(){
        MockServletContext mockContext = new MockServletContext();
        mockContext.setContextPath("/myapp");
        return mockContext;
    }
}
Run Code Online (Sandbox Code Playgroud)