常用的bean作用域
1、单例模式(Spring默认机制)
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
2、原型模式:每次从容器种get的时候,都会产生一个新对象
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
3、request、session、application,在web开发中能用到
Bean的自动装配
1、ByName自动装配
byname时,必须保证所有的bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致。
<bean id="cat" class="com.lyr.pojo.Cat"></bean>
<bean id="dog" class="com.lyr.pojo.Dog"></bean>
<bean id="person" class="com.lyr.pojo.Person" autowire="byName">
<property name="name" value="xm"></property>
</bean>
2、ByType自动装配
bytype时,需要保证所有的bean的class唯一,并且这个bean需要和自动注入的属性的类型一致。
<bean id="cat" class="com.lyr.pojo.Cat"></bean>
<bean id="dog" class="com.lyr.pojo.Dog"></bean>
<bean id="person" class="com.lyr.pojo.Person" autowire="byType">
<property name="name" value="xm"></property>
</bean>
3、使用注解实现自动装配
1、导入约束:context约束
2、配置注解的支持:<context:annotation-config/>
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"
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="com.lyr.pojo.Cat"></bean>
<bean id="dog" class="com.lyr.pojo.Dog"></bean>
<bean id="person" class="com.lyr.pojo.Person" ></bean>
</beans>
@Autowired:
直接在属性上使用即可,也可以用在set方法上使用
@Autowired private Cat cat; @Autowired private Dog dog;
@Autowired(required = false)
如果定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空。其效果相当于@Nullable。
@Autowired相当于xml中设置byname || bytype
如果@Autowired自动装配无法完成,可以使用@Qualifire(value="xxx")来配置@Autowired的使用,指定一个唯一的bean对象注入。
@Resource:
@Resource(name="cat123")
private Cat cat;
@Resource
private Dog dog;
@Resource和@Autowired的区别:
都是用来自动转配的,都可以放在属性字段上
@Autowired默认先通过byType方式实现,而且要求这个对象必须存在
@Resource默认通过byname方式实现,如果找不到名字,再通过bytype实现,都找不到就报错