首页 技术 正文
技术 2022年11月15日
0 收藏 460 点赞 3,746 浏览 1524 个字

一、@Required注解用于检查特定的属性是否设置

1.RequiredAnnotationBeanPostProcessor 为该注解的处理器,即bean后置处理器,检查所有带有该解的bean属性是否设置,如果未设置则抛出异常。

2.在spring配置文件中可以通过<context:annotation-config/>元素自动注册RequiredAnnotationBeanPostProcessor处理器。

3.RequiredAnnotationBeanPostProcessor处理器还能自定义注解用于检查属性,功能与@Required一致

如:

1.定义一个注解类型

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomRequired {}

2.配置RequiredAnnotationBeanPostProcessor,注入自定义注解类型

 <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
<property name="requiredAnnotationType">
<value>CustomRequired</value>
</property>
</bean>

然后就可以使用@CustomRequired 检查属性是否设置,功能与@Required一致。

二、@Autowired根据类型注入bean属性

1.AutowiredAnnotationBeanPostProcessor为该注解的处理器

2.在spring配置文件中可以通过<context:annotation-config/>元素自动注册AutowiredAnnotationBeanPostProcessor处理器

3.默认情况下@Autowired的属性是必须的,如果未设置会抛出异常。可以将@Autowired的required属性设置为false,当未找到匹配的bean,则不设置标注的属性

4.

当注解到数组或List集合中,spring将所有类型匹配的bean注入到该数据或List集合中

@Autowired

private Generator[] generators;

当注解到key为字符串的Map上,则将所有类型匹配的bean注入到map中,bean名称为key。

@Autowired

private Map<String,Generator> generators;

注意:如果在类中指定 @PostConstruct 后置处理器,那么在其中就可以使用@Autowired等依赖注入的对象。

他们在后置处理器执行前就已经依赖注入好了。

5.@Qualifier注解可以限定@Autowired注解到按类型以及名称注入bean。

@Autowired

@Qualifier(“myGenerator”)

private Generator generator;   //则注入类型为Generator并且名称为myGenerator的bean

6.@Autowired注入非集合和数组属性时,如果发现多个匹配类型则报异常。因为按它按类型匹配,发现多个,无法确定注入哪个

三@Resource按名称注入属性,未找到则按类型注入。

1.CommonAnnotationBeanPostProcessor 为该注解的处理器  org.springframework.context.annotation.CommonAnnotationBeanPostProcessor

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,556
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898