依赖注入的方式:1.构造器注入 2.set方式注入 3.c:命名方式 4.p:命名方式
spring中三种装配方式:1.在xmk中显式的配置 2.在java中显式的配置 3.隐式的自动配置(bean)
-
byName:需要保证所有的bean的id都是唯一的,并且这个bean需要和自动注入的属性的set方法的值一致
-
byType:需要保证所有的bean的class都是唯一的,并且这个bean需要和自动注入的属性的类型一致。
使用注解实现自动配置
1.导入约束
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
直接在属性上使用
public class People {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
required默认为true
public class People {
//如果显式的定义了Autowired required为false,说明对象可以为null,否则不允许为空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
@Resource注解
public class People {
@Resource(name="cat2")
private Cat cat;
@Resource
private Dog dog;
private String name;
}
@Resource与@Autowired的区别:
-
都是自动装配,可以放在属性字段上
-
@Autowired通过byType的方式实现,而且要求对象必须存在
-
@Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现。
-
执行顺序不同:@Autowired通过byType的方式实现。@Resource通过byName的方式实现。
-
@Component:组件,等价于 <bean id="user" class="com.pojo.User"/>