java spring required,Spring框架中RequiredAnnotationBeanPostProcessor的用...

RequiredAnnotationBeanPostProcessor是使用Spring的应用程序中不常用的注释.

提供自动装配和要求(默认情况下已启用)行为的@Autowired注释通常是首选.

BeanPostProcessor接口定义了回调方法,您可以实现这些回调方法,以提供自己的(或覆盖容器的默认值)实例化逻辑,依赖关系解析逻辑等.

如果使用RequiredAnnotationBeanPostProcessor,它将强制配置必需的JavaBean属性.

通过Java 5注释检测必需的bean属性:默认情况下,是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类中指定自动装配的情况.

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的使用与非常具体的极端情况有关.这就是为什么您可能找不到很多示例的原因.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值