bean的作用域
1、单例模式(Spring默认机制)
<bean id="user2" class="com.gx.pojo.User" c:name="da" c:age="20" scope="singleton"/>
2、原型模式:每次从容器中get的时候,都会产生一个新对象!
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
3、其余的request、 session、 application,这些个只能在web开发中使用到!
Bean的自动装配
- 自动装配是Spring满足bean依赖一种方式!
- Spring会在上下文中自动寻找,并自动给bean装配属性!
在Spring中有三种装配的方式
1、在xml中显示的配置
2、在java中显示配置
3、隐式的自动装配bean 【重要】
1、测试
环境搭建:一个人有两个宠物!
新建子模块spring-05-Autowired
添加实体类Cat、Dog、People,配置文件beans.xml
2、ByName自动装配
<bean id="dog" class="com.gx.pojo.Dog"/>
<bean id="cat" class="com.gx.pojo.Cat"/>
<!-- byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid! -->
<bean id="people" class="com.gx.pojo.People" autowire="byName">
<property name="name" value="shenshen"/>
</bean>
3、ByType自动装配
<bean class="com.gx.pojo.Cat" />
<bean class="com.gx.pojo.Dog" />
<!-- byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!-->
<!-- byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean !-->
<bean id="people" class="com.gx.pojo.People" autowire="byType">
<property name="name" value="shenshen"/>
</bean>
小结:
-
byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
-
bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
4、使用注解实现自动装配
jdk1.5支持的注解,Spring2.5就支持注解了!
要使用注解须知:
1、导入约束: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 (Spring)容器中存在,且符合名字byname!
科普:
@Nullable
字段标记了这个注解,说明这个字段可以为null;
public @interface Autowired {
boolean required() default true;
}
测试代码
public class People {
如果显示定义了Autowired的required届性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
private String name;
get、set、toString方法省略
}
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候、我们可以使用@Qualifier(value=“xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!
public class People {
如果显示定义了Autowired的required届性为false,说明这个对象可以为null,否则不允许为空
@Autowired
@Qualifier(value = "cat111")
private Cat cat;
@Autowired
@Qualifier(value = "dog222")
private Dog dog;
private String name;
}
@Resource
public class People {
@Resource(name = "cat111")
private Cat cat;
@Resource
private Dog dog;
小结:
@Resource和@Autowired的区别
-
都是用来自动装配的,都可以放在属性字段上
-
@Autowired通过byType的方式实现,而且必须要求这个对象存在! 【常用】
-
@ Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】
-
执行顺序不同:@Autowired通过byType的方式实现。@ Resource默认通过byname的方式实现。