在Spring starters

时间:2017-01-17 02:29:01

标签: java spring spring-mvc spring-bean

TL; DR

向已创建的bean添加一些配置的最佳方法是什么,例如由Spring Auto Configuration机制创建的bean?

用例

我尝试以最佳方式配置ContentNegotiatingViewResolver。我试图在我的MvcConfiguration类中创建该对象的新实例,并在该位置配置所有内容。它奏效了,但我想的是更优雅的东西。

我找到了一个WebMvcAutoConfiguration,用viewResolver(BeanFactory beanFactory)方法创建了一个ContentNegotiatingViewResolver bean。我决定使用它,因为使用现有代码比复制它更好。

但是如何为该bean添加更多配置呢?我试过这样的事情:

@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {

    @Autowired
    private ContentNegotiatingViewResolver contentNegotiatingViewResolver;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    @Bean
    public ViewResolver jsonViewResolver() {
        return new JsonViewResolver();
    }

    @PostConstruct
    public void postConstruct() {
        contentNegotiatingViewResolver.setViewResolvers(Arrays.asList(jsonViewResolver(), thymeleafViewResolver));
    }
}

并在@PostConstruct方法中配置所有内容,但我想知道,如果这是最好的方法。

1 个答案:

答案 0 :(得分:0)

通过构造函数使用自动装配。

        @Configuration
        public class MvcConfiguration extends WebMvcConfigurerAdapter {


            private ContentNegotiatingViewResolver contentNegotiatingViewResolver;

            private ThymeleafViewResolver thymeleafViewResolver;

           @Autowired
           public MvcConfiguration(ContentNegotiatingViewResolver  contentNegotiatingViewResolver,ThymeleafViewResolver thymeleafViewResolver){

             this.contentNegotiatingViewResolver=contentNegotiatingViewResolver;
             this.thymeleafViewResolver=thymeleafViewResolver;
             ViewResolver jsonViewResolver= new JsonViewResolver();
             this.contentNegotiatingViewResolver.setViewResolvers(Arrays.asList(jsonViewResolver, thymeleafViewResolver));

        }




  }

替代解决方案:

    @Configuration
    @EnableWebMvc
    public class MvcConfiguration extends WebMvcConfigurerAdapter {



        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {

            registry.enableContentNegotiation();
            registry.viewResolver(jsonViewResolver());
            super.configureViewResolvers(registry );
        }

    }