我正在尝试使用我的上下文在运行时注册SpringMvc配置WebMvcConfigurationSupport
类。通常情况下,如果我没有要求在运行时注册它,我会在类上使用@Configuration
注释,但我需要注册一个特定的实例来控制运行时的一些覆盖(不使用静力学。)
查看此处的文档:http://docs.spring.io/spring/docs/4.0.5.RELEASE/javadoc-api/org/springframework/context/annotation/Configuration.html我似乎可以通过ConfigurationClassPostProcessor
方法使用context.addBeanFactoryPostProcessor()
将WebMvcConfigurationSupport
的实例添加到在运行时的上下文,但我不能让我的生活得到它。
我想要做的事实际上是否可行,有没有人有例子?
修改
所以我可以这样做:
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
public static List<HttpMessageConverter<?>> converters;
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.addAll(this.converters);
}
}
WebMvcConfig.converters = //...
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(WebMvcConfig.class);
但我不喜欢在那里使用静态,这意味着我不能同时使用WebMvcConfigurationSupport
类的多个实例。 (即创建多个Web服务器的代码相同)
我真正想要的是这样的事情:
public class WebMvcConfig extends WebMvcConfigurationSupport {
private List<HttpMessageConverter<?>> converters;
public WebMvcConfig setConverters(List<HttpMessageConverter<?>> converters) {
this.converters = converters;
return this;
}
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.addAll(this.converters);
}
}
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register((new WebMvcConfig()).setConverters(...));
最终的想法是我正在构建一种&#34; web服务器&#34;生成器工厂,它会快速为我提供一个服务器,我只需要给它一些参数和一些控制器(配置由工厂负责)....因为我发现我在很多使用相同的代码项目。
答案 0 :(得分:0)
我找不到答案,但我找到了一个我现在很满意的解决方法:
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Autowired
private WebMvcConfigDetails details;
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.addAll(details.converters);
}
}
WebMvcConfigDetails
需要通过以下方式添加到上下文中:
context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.registerSingleton("webMvcConfigDetails", webMvcConfigDetails);
}});