我正在尝试在 Spring
Boot 应用程序中实现转换器,但由于某种原因,我对 addFormatters(FormatterRegistry formatterRegistry)
的重写从未被调用。令人困惑的是,调用了其他重写的方法,addInterceptors
工作得很好。此应用程序已启用安全性。
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = {"com.company.web"})
public class WebMvcConfig extends WebMvcConfigurerAdapter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
@Inject
private TenantIdentifierInterceptorAdapter multiTenancyInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
logger.info("adding interceptor");
registry.addInterceptor(multiTenancyInterceptor);
}
//THIS IS NOT CALLED
@Override
public void addFormatters(FormatterRegistry formatterRegistry) {
logger.info("adding converters");
formatterRegistry.addConverter(new StringToPersonConverter());
}
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {"classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/"};
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS)
.setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver());
}
@PostConstruct
public void init() {
requestMappingHandlerAdapter.setIgnoreDefaultModelOnRedirect(true);
}
}
出于某种原因,如果我将此代码添加到文件中,则会触发格式化程序代码,但我收到错误“需要 ServletContext 来配置默认 servlet 处理”,并且应用程序将无法编译。
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
最佳答案
您是否使用父类(super class) WebMvcConfigurationSupport 配置了 bean?
如果您这样做,它将禁用 WebMvcAutoConfiguration Bootstrap。
检查此代码:
@Configuration
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
关于java - Spring addFormatters 未调用 WebMvcConfigurerAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41736050/