1.p标签
xmlns:p="http://www.springframework.org/schema/p"
p标签是根据set注入
2.c标签
xmlns:c="http://www.springframework.org/schema/c"
c标签是根据构造方法注入
3.spring默认是单例模式,可以用scope属性来设置
(1)单例模式
<bean id="student" class="com.pojo.Student" c:name="zhangsan" c:age="19" scope="singleton"></bean>
prototype是原型模式:每次调用都是新的一个对象
<bean id="student" class="com.pojo.Student" c:name="zhangsan" c:age="19" scope="prototype"></bean>
其它只能在web中使用!!!!
三种自动装配
环境搭配:两个动物,一个zoo
public class Cat {
public void show(){
System.out.println("喵喵喵~~~~~~~~");
}
}
public class Dog {
public void show(){
System.out.println("汪汪汪~~~~~~~~");
}
}
public class Animal {
private Cat cat;
private Dog dog;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
}
@Test
public void text(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("animalbeans.xml");
Animal animal = context.getBean("animal", Animal.class);
animal.getCat().show();
animal.getDog().show();
}
第一种:
<bean id="cat" class="com.bean.Cat"></bean>
<bean id="dog" class="com.bean.Dog"></bean>
<bean id="animal" class="com.bean.Animal">
<property name="cat" ref="cat"></property>
<property name="dog" ref="dog"></property>
</bean>
第二种:是byname,会自动查找和自己对象set后面对应的id值
id=’‘cat’’
在animal中是setCat
<bean id="animal" class="com.hujia.bean.Animal" autowire="byName"></bean>
第三种是bytype查找和自己对象属性相同的bean,就是按Bean的Class的类型
<bean id="animal" class="com.hujia.bean.Animal" autowire="byType"></bean>
注解:自动装配
@Autowired是按类型自动转配的,不支持id匹配
需要导入 spring-aop的包!
如果允许对象为null,设置required = false,默认为true
@Autowired(required = false)
@Qualifier
在加上@Autowired的基础上再加上@Qualifier是根据byname的方式进行自动装配
@Resource
- @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
- 其次再进行默认的byName方式进行装配;
- 如果以上都不成功,则按byType的方式自动装配。
- 都不成功,则报异常。