1.通过ID自动装配
Spring Bean自动装配可以自动搜索beans.xml中的bean,进行自动装配,这样就可以使开发人员不必显示的声明它
例如,Person.java中包含了猫和狗的实体类对象
public class Person { private String name; private Dog dog; private Cat cat; public String getName() { return name; } public void setName(String name) { this.name = name; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } public Cat getCat() { return cat; } public void setCat(Cat cat) { this.cat = cat; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", dog=" + dog + ", cat=" + cat + '}'; } }
现在我们可以通过自动装配机制引入猫和狗的类对象:
autowire="byName"是通过bean的ID引入的
<bean id="cat" class="top.imustctf.pojo.Cat"/> <bean id="dog" class="top.imustctf.pojo.Dog"/> <bean id="person" class="top.imustctf.pojo.Person" autowire="byName"> <property name="name" value="dahe"/> </bean>
测试类:
@Test public void test() { // 获取Spring的上下文对象 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = context.getBean("person", Person.class); person.getDog().shout(); // 汪汪汪! person.getCat().shout(); // 喵喵喵! }
2.通过类型自动装配
autowire="byType"是通过bean的class引入的
<bean id="cat" class="top.imustctf.pojo.Cat"/> <bean id="dog" class="top.imustctf.pojo.Dog"/> <bean id="person" class="top.imustctf.pojo.Person" autowire="byType"> <property name="name" value="dahe"/> </bean>
3.注解自动装配
注解自动装配的前期环境配置:
导入context约束
xmlns:context="http://www.springframework.org/schema/context"
以及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">
配置注解的支持
最终的配置文件效果:
<?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
Autowired
可以实现自动装配机制:
很简单!我们只需要在pojo类中添加如下的注解即可实现自动装配:
@Autowired private Dog dog; @Autowired private Cat cat;
现在我们可以去掉可恶的autowire
参数,来尽情测试吧!
<bean id="person" class="top.imustctf.pojo.Person"> <property name="name" value="dahe"/> </bean>
Autowired默认按照Type进行匹配,如果配置文件中存在相同的类型,我们可以使用Qualifier
注解来指定使用id进行匹配
<bean id="myDog" class="top.imustctf.pojo.Dog"/>
@Autowired @Qualifier(value = "myDog") private Dog dog;