gpt4 book ai didi

spring - 如何使用注释覆盖 xml 中定义的 spring bean?

转载 作者:行者123 更新时间:2023-12-04 11:39:17 24 4
gpt4 key购买 nike

我有一个现有的 bean overrideBean定义于 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;
}

}

使用上面的代码,来自 spring.xml 的 bean config 总是由 context.getBean 实例化和返回称呼。

bean 可以通过在 @ImportResource 中包含另一个 XML 配置文件来覆盖。但是我更愿意找到使用注释的解决方案会更干净。

最佳答案

我正在使用通过 xml 配置的旧应用程序(spring 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;
}
}

关于spring - 如何使用注释覆盖 xml 中定义的 spring bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18400850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com