6.Bean的作用域
作用域
1.单例模式 (Spring默认机制) scope="singleton
<bean id="user2" class="com.txy.pojo.User" c:name="狂神" c:age="18" scope="singleton"/>
2.原型模式:每次从容器中get的时候,都会产生一个新对象
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
3.其余的request、session、application这些只能在web开发中使用到
7.Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中自动寻找,并自动给bean转配属性
在Spring中有三种装配方式:
1.在xml中显示的配置
2.在java中显示配置
3.隐式的自动装配bean【重要】
测试
1.环境搭建:新建模块spring-05-Autoweird
一个人有两个宠物 Dog、Cat、People实体类
beans.xml中配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.txy.pojo.Cat"/>
<bean id="dog" class="com.txy.pojo.Dog"/>
<bean id="people" class="com.txy.pojo.People">
<property name="name" value="小谭呀"/>
<property name="dog" ref="dog"/>
<property name="cat" ref="cat"/>
</bean>
</beans>
执行结果
通过byName自动装配,照样能执行出结果
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
byType自动装配
autowire=“byType”
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean。
但当id出现两个时会报错
注解实现自动装配
要使用注解须知: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>
3.@Autoweird 直接在属性上使用或set方法上
使用@Autoweird 我们可以不写set方法,前提是这个自动装配的属性在IOC容器(Spring)中 存在,且符合名字byName
您还可以指定@Qualifier对单个构造函数参数或方法参数的注释,如下例所示:
package com.txy.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class People {
//将Dog Cat自动注入
@Autowired
private Cat cat;
@Autowired
@Qualifier(value = "dog1")
private Dog dog;
private String 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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
如果@Autoweird自动装配环境比较复杂,自动装配无法通过一个注解@Autoweird完成时,我们可以使用@Qualifier(value=xxx)来配合@Autowerid使用,指定一个唯一的bean对象注入
还有例如@Resource(name=xxx)也可以注入
小结:@Resource和@Autoweird的区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autoweird是通过byType方式实现,而且必须要求这个对象存在
- @Resource默认通过byName方式实现,如果找不到名字,则通过byType方式实现,如果两个都找不到就报错
- 执行顺序不同:@Autoweird通过byType实现。@Resource默认通过byName方式实现