Bean 作用域
通过scope来设置
<bean id="user" class="com.zxw.pojo.Hello" p:str="zxw" c:s="zxw" scope="singleton"/>
单例 singleton 原型 prototype web开发中使用的 请求request 会话session 应用application websocket
singleton 默认实现
单例模式。 创建的实例只有一个 单线程多用
prototype
原型模式 每次从容器中get的时候,都会产生一个新的对象。多线程多用
request
session
application
websocket
spring 装配的三种的方式
1.在xml中显示的配置
2.在java中显示配置(set注入)
3.隐士的自动装配bean. 重点
Bean的自动装配
是spring满足bean依赖的一种方式
spring会在上下文中自动寻找,并自动给bean装配属性
autowire
byName 会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id. 需要保证bean的id唯一
<bean id="cat" class="com.zxw.pojo.Cat"></bean>
<bean id="dog" class="com.zxw.pojo.Dog"></bean>
<bean id="people" class="com.zxw.pojo.People" autowire="byName">
<property name="name" value="zxw"/>
</bean>
byType 会自动在容器上下文中查找,和自己对象属性类型相同的bean 适合属性 必须保证类型全局唯一 bean的class唯一*
<bean id="cat" class="com.zxw.pojo.Cat"></bean>
<bean id="dog" class="com.zxw.pojo.Dog"></bean>
<bean id="people" class="com.zxw.pojo.People" autowire="byType">
<property name="name" value="zxw"/>
</bean>
contructor 构造器
使用注解实现自动配置
jdk1.5支持注解,spirng2.5支持的注解
使用注解须知:1.导入约束
xmlns:context=“http://www.springframework.org/schema/context”
2.配置注解的支持
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/>
</beans>
@AutoWired
直接在属性上使用即可,也可以在set方式上使用
使用autowired可以不编写set方法了,前提是这个自动装配的属性在IOC容器中存在,且符合名字byName
@Nullable 字段标记了这个注解 参数可以为空
@AutoWired(required = false)如果显示设置了autowired的requied为false则这个对象可以为null,否则不允许为空
public @interface Autowired {
boolean required() default true;
}
测试
public class People {
@Autowired
private Dog dog;
@Autowired
private Cat cat;
private String name;
如果@autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value=“xxx”)配合@autowired的使用,指定一个唯一的bean对象
public class People {
@Autowired
private Dog dog;
@Autowired
@Qualifier(value = "cat")
private Cat cat;
private String name;
@Resource注解 Java的注解
@Resource(name = "dog")
private Dog dog;
@Resource和@Autowired的区别:
都是用来自动装配的,都可以放在属性字段上
@Autowired通过bytype的方式实现,必须要求这个对象存在
@Resource默认通过byname的方式实现,如果找不到名字,则通过bytype方式实现,如果连个都找不到就会报错
执行顺序不同:@Autowired通过bytype的方式实现