Bean的自动装配
自动装配是Spring满足bean依赖的一种方式
Spring会在上下文自动寻找,并自动给bean装配
1.在xml中显示的配置
2.在java中显示的配置
3.隐式 的自动装配bean【重要】
测试
autowire="byName"
autowire="byType"
byName:在容器中自动查找,和自己set方法还没值对应的beanid
byType:在容器中自动查找,和自己对象属性类型相同的bean
小结:
byName:需要保证所有bean的id唯一
byType:需要保证所有bean的class唯一
注解实现自动装配
1.导入约束 context约束
2.配置注解的支持
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
@Autowired
直接在属性上使用即可!也可以在set方法上使用!
自动装配通过类型(byType)、名字(byName)
@Autowired
private Cat cat;
@Autowired
@Qualifier(value="dog2222")
private Dog dog;
如果装配环境比较复杂
我们可以通过@Qualifier(value=“xxx”)去配置@autowied的使用
指定一个唯一的bean对象注入!
@Resource
自动装配通过名字、类型
@Resource(name="cat2")
private Cat cat;
@Resource
private Dog dog;
@Nullable 说明这个字段可以为null
Spring使用注解开发
spring4之后,使用注解开发必须要保证aop的包导入了
使用注解需要导入context约束,增加注解的支持
<!--指定要扫描的包,这个包下的注解才会生效-->
<context:component-scan base-package="com.kuang.pojo"/>
@Component
组件,放在类上,说明这个类被Spring管理了,就是bean
@Value()
@Value(“kuangshen”)
相当于<property name="name" value="kuangshen"/>
@Component
public class User{
@Value("kuangshen")
public String name;
}
@Component
public class User{
public String name;
@Value("kuangshen2")
public void setName(String name){
this.name = name;
}
}
@Component几个衍生注解,在web开发中,会按照MVC三层架构分层!
- dao 【@Repository】
- service 【@Service】
- controller 【@Controller】
这四个注解功能都是一样的,都是代表将某个类注册注册到spring容器中装配Bean
作用域
@Scope
xml与注解最佳实践:
- xml用来管理bean
- 注解只负责完成属性的注入