一·使用xml自动装配:
<bean id="cat" class="com.he.pojo.Cat"/>
<bean id="dog" class="com.he.pojo.Dog"/>
<!--显示装配-->
<bean id="people" class="com.he.pojo.People">
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
<!--自动装配-->
<bean id="people2" class="com.he.pojo.People" autowire="byName" scope="Prototype">
</bean>
可以autowire=“byName”,"byType",前者通过名称,后者通过类型。
scope用来表示bean的作用域,单例和原型。
二·使用注解实现自动装配
1.导入相应的语句,实现注解支持
<?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>
2.配置people和dog和cat的bean:
<bean id="cat" class="com.he.pojo.Cat"/>
<bean id="cat1" class="com.he.pojo.Cat"/>
<bean id="cat2" class="com.he.pojo.Cat"/>
<bean id="dog" class="com.he.pojo.Dog"/>
<bean id="dog1" class="com.he.pojo.Dog"/>
<bean id="dog2" class="com.he.pojo.Dog"/>
<bean id="people" class="com.he.pojo.People">
</bean>
3.自动装配:
@Autowired:可以加在属性上,可以加在set方法上和构造器上,加在方法上可以不需要set方法,它是基于反射机制实现的,先byType,如果Type不统一,再byName,可以与@Qualifier(value = "dog2")配套使用指定具体的名称,@Autowired(required = false)表示该属性可以为null。
与@Nullable注解作用类似。
public class People {
//自动装配
@Autowired(required = false)
private Cat cat;
// @Autowired
// @Qualifier(value = "dog2")
@Resource(name = "dog2")
private Dog dog;
@Override
public String toString() {
return "People{" +
"cat=" + cat.shut() +
", dog=" + dog.shut()+
'}';
}
}
@Resource与@Autowired相同,不同是,使用@Resource(name = "dog2")中name属性表示指定的对象名称装配。
三·使用注解创建bean
加入配置扫描相应包下的bean
<context:component-scan base-package="com.he.pojo"/>
在实体类前面加上@Component注解即可,注册的bean的id默认为类名首字母的小写,方便于自动装配,对于属性的注入,只需要在属性上加上@value注解即可,当然也可以写在set方法上。
@Component
public class Cat {
public String shut(){
return "miao~";
}
}
@Component
public class Dog {
public String shut(){
return "wang~";
}
}
@Component
public class People {
@Value("何志康")
private String name;
//自动装配
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
@Override
public String toString() {
return "People{" +
"cat=" + cat.shut() +
", dog=" + dog.shut()+
'}';
}
}
这样一来,三个类就被注入到xml文件中了,外部就可以从容器取出对象并使用,
Component的衍生注解:
作用相同,只是起到标志性的作用:
@Component
@Repository //标志dao层的类
@Service //标志service层的类
@Controller //标志controller层的类
@Scope:
@Scope("Singleton")或@Scope("Prototype")加在类的前面表示作用域。