您的位置:首页 > 编程语言 > Java开发

spring详解:使用注解方式注入属性

2017-08-10 08:23 771 查看
之前介绍过如何在<bean>标签中注入该bean需要使用的属性,那么从spring3.0以后支持注解的方式进行注入,十分便捷,只需要在类中要注入的属性上或者set方法上添加注解即可注入该属性。

首先准备:导入aop的包+加约束+声明启动注解

包名:spring-aop-4.2.4.RELEASE.jar       因为有关注解的操作封装在此包中

约束:加的是context的约束,可以在spring解压的约束文件中去找,该约束如下

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" >


开启注解   

此种注解会扫描属性和方法上的注解--------后续的spring详解中介绍另一种注解扫描,可以扫描类、属性、方法上的注解

<!-- 开启注解驱动 -->
<context:annotation-config/>


两个注解:

@Resources

注解加在属性上

在bean中定义要注入bean的属性,不需要提供set方法





如果指定了name属性,在spring容器中找到了对应的bean,就能注入,没有找到就会报错



@Resource不是Spring的注解,而是javax下的

注解加在set方法上





如果指定了@Resource的name如果匹配不上就会报错,不会再按类型去匹配



@Autowired(配合@Qualifier)

注解加在属性上

在bean中定义要注入bean的属性,不需要提供set方法





注解加在set方法上

使用和加在属性上类似



另外:@Autowired注解可以声明(required="true")或者声明为false。表明 此属性bean的注入时,bean是否必须存在(被定义)。默认是true。

小结:使用注解的方式进行注入,@Resource会先匹配id与属性名或方法中的参数、方法名,若匹配不到则按照接口与实现类的关系进行注入,若出现多个实现类则注入失败。@Autowired注解的方式是直接按照接口与实现类的关系进行注入,若有多个实现类则配合@Qualifier的value值进行指定注入哪一个实现类的bean。那么在实际开发中,无论使用哪种注解注入,最好是指定注入bean的id,增加程序的可阅读性与可维护性

spring的再次回顾总结,若有详述不当之处,感谢您私信纠正
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐