如何在Java (Spring3.1)中启用@Required注释?不是在xml中,而是通过Java。另外,我在哪个注释中添加了这个启用功能?在@Feature (在@FutureConfiguration中)或@Bean (在@Configuration中)下?
编辑:
@Feature
public MvcAnnotationDriven annotationDriven(ConversionService conversionService) {
return new MvcAnnotationDriven().conversionService(conversionService)
.argumentResolvers(new CustomArgumentResolver());
}这会启用所有注释吗?
发布于 2011-03-22 08:36:16
@anubhava的答案有效,但他引用了Spring2.0手册,该手册已有5年历史。
在XML中,Spring3.x有一种更优雅的方法:<context:annotation-config/>。这还启用了您可能需要的全部其他特性,而RequiredAnnotationBeanPostProcessor只启用了一些功能。
见弹簧3.x手册。
如果您使用的是@Bean-style配置,那么应该已经启用了像@Required这样的注释,因为@Bean就是这样工作的。然而,这可能是一个bug -Spring3.1还处于早期测试阶段,其中的大部分可能会被破坏。
除非你真的知道自己在做什么,否则我强烈建议你坚持3.0.x。
发布于 2011-03-22 04:02:28
来自弹簧手册:
还有最后一点(很小,很小)的Spring配置,它实际上需要“打开”这种行为。仅仅注释类的“setter”属性是不够的。您需要启用一个组件,该组件知道@Required注释,并且能够适当地处理它。 这个组件是RequiredAnnotationBeanPostProcessor类。这是一个特殊的BeanPostProcessor实现,它具有@ required感知,并且实际上提供了‘如果没有设置所需的属性就会爆炸’的逻辑。配置非常容易;只需将以下bean定义放到Spring配置中即可。
<bean class=
"org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>请查看:http://static.springsource.org/spring/docs/2.0.x/reference/metadata.html
发布于 2011-03-22 09:06:05
如果不想使用XML,请使用AnnotationConfigApplicationContext:
独立的应用程序上下文,接受带注释的类作为输入-特别是
@Configuration-annotated类,但也使用javax.inject注释接受普通的@Components和JSR-330兼容的类。允许逐个注册类(register(java.lang.Class...))以及类路径扫描(scan(java.lang.String...))。 对于多个配置类,以后类中定义的Bean方法将覆盖先前类中定义的方法。这可以通过额外的配置类来有意地覆盖某些bean定义。
示例代码:
ConfigurableApplicationContext applicationContext =
new AnnotationConfigApplicationContext(
"com.mycompany.package1",
"com.mycompany.package2",
"com.mycompany.package3"
// etc.
);
applicationContext.refresh();https://stackoverflow.com/questions/5386618
复制相似问题