我真的很喜欢 spring 和 @Configuration 风格来摆脱基于 xml 的配置。我成功地将它用于服务和存储库层。我还喜欢依赖注入功能和 JDO/JPA/Jdbc 实用程序!
我真正不明白的是,Spring WebMVC 是如何工作的。对我来说,无法控制的魔法太多了。(并且使用@EnableAutoConfiguration 引入了更多魔法。易于原型设计,难以维护)。
这就是我配置我的 webapp 的方式:
public class SpringWebBooter implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigApplicationContext rootContext = new AnnotationConfigApplicationContext();
rootContext.register(SpringConfiguration.class); //main configuration class for all beans
rootContext.refresh();
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.setParent(rootContext);
ctx.register(SpringWebConfiguration.class); //web context configuration class
ServletRegistration.Dynamic api = servletContext.addServlet("api", new DispatcherServlet(ctx));
api.setLoadOnStartup(1);
api.addMapping("/api/*");
}
}
现在我想添加类型转换器和 httpMessageConverters,所以在 SpringWebConfiguration 类中我尝试了:
@EnableWebMvc
@Configuration
@ComponentScan
public class SpringWebConfiguration {
//works but feels very *magic*
@Autowired
public void configureConversionService(FormattingConversionService conversionService) {
conversionService.addConverter(new PointConverter(GEOMETRY_FACTORY));
conversionService.addConverterFactory(new StringToEnumConverterFactory());
}
//not working yet
@Bean
public MappingJackson2HttpMessageConverter createJsonMessageConverter() {
ObjectMapper o = new ObjectMapper();
o.enable(SerializationFeature.INDENT_OUTPUT);
MappingJackson2HttpMessageConverter c = new MappingJackson2HttpMessageConverter();
c.setObjectMapper(o);
return c;
}
}
我更希望直观的是在构建调度程序 servlet 时添加类型和消息转换器。这比一些可疑的自动装配或 bean 创建要清楚得多。我一直“希望” Dispatcher Servlet 在内部为我的 bean 拍照,但这通常只是反复试验。是否可以以更直接的方式设置 spring Mvc?例如,使用更少的魔法和更具体的实例化和#addHttpMessageConverter(...) 调用?
ExceptionResolvers、RequestHandler 和 RequestAdapter 基本相同。
简