如您所知,我们可以创建单例bean,如下所示:
@Bean(name = "localeResolver")
public LocaleResolver cookieLocaleResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setDefaultLocale(new Locale("ko"));
return localeResolver;
}
但是对于ContentNegotiationResolver,我们建议使用以下代码来实现自3.2之后的默认ContentNegotiationResolver
@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
contentNegotiatingViewResolver.setOrder(0);
contentNegotiatingViewResolver.setContentNegotiationManager(manager);
List<View> views = new ArrayList<View>();
views.add(new MappingJackson2JsonView());
contentNegotiatingViewResolver.setDefaultViews(views);
return contentNegotiatingViewResolver;
}
如您所见,上面的方法有参数ContentNegotiationManager
以下是我的问题:上述@bean
方法的客户端如何创建参数?客户端注入参数ContentNegotiationManager
的属性值是什么?
spring框架被指示创建一个ContentNegotiation bean而不是ContentNegotiationManger。
提前谢谢。
答案 0 :(得分:0)
如果要将contentNegotiatingViewResolver放在spring上下文中并且它需要ContentNegotiationManager作为构造函数参数,那么你别无选择,只能注入一个同样存在于spring上下文中的文件。
如果您想让客户端指定ContentNegotiationManager,那么您需要返回一个具有客户端可以调用的方法的类。我能想到的最简单的方法是将一个创建ViewResolver的方法包装在一个简单的类中,可能使用@component注释进行注释,如下所示:
@Component
public class MyViewResolver {
List<View> views = new ArrayList<View>();
public ViewResolver getResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
contentNegotiatingViewResolver.setOrder(0);
contentNegotiatingViewResolver.setContentNegotiationManager(manager);
List<View> views = new ArrayList<View>();
views.add(new CommonMappingJackson2JsonView());
contentNegotiatingViewResolver.setDefaultViews(views);
return contentNegotiatingViewResolver;
}
}