Bean的作用域
(scope不设置默认为单例)
- 单例模式singleton(spring默认机制)
- 原型模式prototype(每次从容器中get的时候,都会产生一个新对象)
<bean id="address" class="pojo.Address" scope="singleton"></bean>
Bean的自动装配
spring会在上下文中自动寻找并自动给bean装配属性
装配方式有三种
- xml显示装配
<bean id="cat" class="pojo.Cat"></bean>
<bean id="dog" class="pojo.Dog"></bean>
<bean id="people" class="pojo.People">
<property name="name" value="dhy"></property>
<property name="cat" ref="cat"></property>
<property name="dog" ref="dog"></property>
</bean>
- java注解显示装配
使用注解步骤
- xml导入context约束
- 配置注解的支持 <context:annotation-config/>
<?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/> <bean id="cat" class="pojo.Cat"></bean> <bean id="dog" class="pojo.Dog"></bean> <bean id="people" class="pojo.People"></bean> </beans>
import org.springframework.beans.factory.annotation.Autowired;
public class People {
private Cat cat;
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Autowired
private Dog dog;
private String name;
}
- 隐式的自动装配:autowire
byType自动装配:spring自动在上下文中查找和自己对象属性类型相同的bean
<bean id="cat" class="pojo.Cat"></bean>
<bean id="dog" class="pojo.Dog"></bean>
<bean id="people" class="pojo.People" autowire="byType">
<property name="name" value="dhy"></property>
</bean>
byName自动装配:spring自动在上下文中查找和自己对象set方法后面的值相对应的bean的id
<bean id="cat" class="pojo.Cat"></bean>
<bean id="dog" class="pojo.Dog"></bean>
<bean id="people" class="pojo.People" autowire="byName">
<property name="name" value="dhy"></property>
</bean>