Spring自动装配方式及注解
Spring自动装配复习笔记
<bean id="user" class="com.Yue.pojo.User" autowire="byName"> <property name="str" value="Yue"/> </bean>
使用xml方式
autowire byName(按名称自动装配)
当一个bean节点中带有autowrie byName的属性时
将查找bean本身所有set方法名,获取将set去掉并且首字母小写的字符串
如果没有取出来的字符串相匹配将会报空指针异常
autowire="byName"
autowire byType(按类型自动装配)
确保同类型的对象,在spring容器中保持唯一,如果不唯一将报错
autowire="byType"
使用注解方式
<context:annotation-config/>:开启属性注解支持
<context:component-scan base-package="com.Yue.pojo"/>:指定注解扫描包下的注解
@Component("user"):相当于配置文件中<bean id="user" class="当前注解的类"/>
@Autowried
按类型自动装配(byType) 不支持id匹配
@Autowried(request=false)
request=false:对象可为null;
request=true:对象不能为空;(缺省值)
@Autowired(required = false) private Yue yue;
@Qualifier
按名称自动装配(byName)
不能单独使用,需跟@Autowired()搭配使用
@Autowired()匹配多个类型的值时可使用@Qualifier()取其一
@Autowired @Qualifier(value = "yue") private Yue yue;
@Resource
name:指定名称按照byName方式查找装配
先进行byName查找 失败;再进行byType查找
public class User {
//如果允许对象为null,设置required = false,默认为true
@Resource(name = "cat2")
private Cat cat;
@Resource
private Dog dog;
private String str;
}
@Autowried()与@Resource()
相同之处:
都可以用来装配bean,可以写在字段上或写在stter方法上
都是以注解方式注入对象
不同之处:
@Autowried() 默认按类型装配(Spring规范)
@Resource() 默认按名称查找(J2EE复返)
执行方式不同 @Autowired()是byType @Resource()是byName
PS:J2EE是基于Java组件技术的企业应用系统开发规范,需按照规范开发api与组件
衍生注解
-
@Component :pojo层 @Controller:web层 @Service:service层 @Repository:dao层 将注解的类交与Spring容器管理装配
