- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是Spring框架的初学者。我已经开始学习 Spring 框架几周了。我没有得到RequiredAnnotationBeanPostProcessor 的任何正确解释。请有人帮助我提供一些RequiredAnnotationBeanPostProcessor 的示例以及在哪里使用它。提前致谢。
最佳答案
RequiredAnnotationBeanPostProcessor
是使用 Spring 的应用程序中不常用的注释。
通常首选提供 Autowiring 和所需(默认启用)行为的@Autowired 注释。
RequiredAnnotationBeanPostProcessor
是一个 BeanPostProcessor 实现。
BeanPostProcessor
接口(interface)定义了回调方法,您可以实现这些方法来提供您自己的(或覆盖容器的默认值)实例化逻辑、依赖解析逻辑等。
对于 RequiredAnnotationBeanPostProcessor
,它强制要求已配置所需的 JavaBean 属性。
必需的 bean 属性通过 Java 5 注释进行检测:默认情况下,使用 Spring 的 Required
注释。
简而言之,它可以确保声明“必需”属性的 bean 实际上已配置了值。请注意,该值可能为 null
。
例如假设这个模型类:
public class Foo {
private Bar bar;
@Required
public void setBar(Bar bar) {
this.bar = bar;
}
}
如果在bean初始化期间从未调用setBar()
,则会抛出org.springframework.beans.factory.BeanInitializationException
。
例如,此 bean 配置将触发异常抛出:
@Configuration
public class MyConfig {
@Bean
public Foo getFoo() {
return new Foo();
}
}
当然,如果您将 @Autowired
添加到 setBar() 并具有可解析的依赖项,那就没问题了:
public class Foo {
private Bar bar;
@Autowired
@Required
public void setBar(Bar bar) {
this.bar = bar;
}
}
因此,我们可以认为 RequiredAnnotationBeanPostProcessor
的一个很好的用例是您不希望/无法在 bean 类中指定 Autowiring 的情况。
另请注意 RequiredAnnotationBeanPostProcessor
还提供了一个附加功能,该功能符合 javadoc 的主要目标:
The motivation for the existence of this BeanPostProcessor is to allow developers to annotate the setter properties of their own classes with an arbitrary JDK 1.5 annotation to indicate that the container must check for the configuration of a dependency injected value.
这意味着您可以指定另一个注解@Required
来指示所需的约束。RequiredAnnotationBeanPostProcessor
实际上定义了一个 setRequiredAnnotationType()
方法,您可以重写该方法来设置要使用的注释。
如您所见,RequiredAnnotationBeanPostProcessor
的使用与非常具体的极端情况相关。这就是为什么您可能找不到很多相关示例。
关于spring - Spring框架中的RequiredAnnotationBeanPostProcessor有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49097648/
我是一名优秀的程序员,十分优秀!