我想在AnnotationMethodHandlerAdapter中自定义下面的方法,该方法用于在spring中映射带注释的方法。
public static boolean checkHeaders(String [] headers,HttpServletRequest request){}
如何在spring中配置我的适配器,我已经覆盖了checkHeaders方法。
答案 0 :(得分:2)
<mvc:annotation-driven />
标记的作用通常是在应用程序上下文中自动注册AnnotationMethodHandlerAdapter
和关联的bean。
如果要手动注册自己的自定义AnnotationMethodHandlerAdapter
子类,则应删除<mvc:annotation-driven />
标记并在dispatcher-servlet.xml中声明自定义bean。
<bean class="some.package.MyCustomAnnotationMethodHandlerAdapter">
<property name="someProperty" value="someValue"/>
</bean>
如果您不删除<mvc:annotation-driven/>
,那么您将在应用程序上下文中获得两个AnnotationMethodHandlerAdapter
bean - 而您的自定义bean将被忽略。
有一篇非常好的帖子here讨论了如何自定义AnnotationMethodHandlerAdapter
并使用BeanPostProcessor
来修改默认AnnotationMethodHandlerAdapter
的替代方法。< / p>
值得指出的是,{3.2}在Spring 3.2中被弃用,而不是AnnotationMethodHandlerAdapter
答案 1 :(得分:0)
我遇到了与Will描述的相同的麻烦,并且解决了问题,这是恕我直言,比文章here中提出的更简单,更紧凑:
@Component( “customHttpMessageConverter”) 公共类DemoHttpMessageConverter扩展MappingJacksonHttpMessageConverter {
@Autowired
AnnotationMethodHandlerAdapter handlerAdapter; // <-- will be injected by Spring
@PostConstruct
public void init() {
// here the field 'handlerAdapter' is already injected
// and you can either extend or substitute the list of message-converters
handlerAdapter.setMessageConverters(new HttpMessageConverter[] {this});
}
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
// we use JAXB in our project, but you can provide your own logic here
// or just return 'true' if you are sure that @ResponseBody and @RequestBody are used properly
return clazz.isAnnotationPresent(XmlRootElement.class);
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
// ... the same as with 'canRead' ...
return clazz.isAnnotationPresent(XmlRootElement.class);
}
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
String inputMessageStr = IOUtils.toString(inputMessage.getBody());
return customDeserialize(inputMessageStr);
}
@Override
protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
String outputMessageStr = customSerialize(inputMessageStr);
IOUtils.write(outputMessageStr, outputMessage.getBody(), JsonEncoding.UTF8.getJavaName());
}
public Object customDeserialize(String json) {
// your own de-serialization
}
public String customSerialize(Object obj) {
// your own serialization
}
}