自动装配简介
当我们对象属性是一个对象类型时,自动装配可以为我们自动匹配把对象注入赋值到属性,我们就可以不需要手动写注入的配置了。
自动装配有两种方法,
- 一种是在bean上添加autowire属性
- 一种是使用注解
第一种在bean上添加autowire属性
这里使用到了一个p命名空间注入:
xmlns:p="http://www.springframework.org/schema/p"
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd"
>
<bean id="cat" class="cn.mao.pojo.Cat"/>
<bean id="dog1" class="cn.mao.pojo.Dog"/>
<!--自动装配
autowire="byName"
byName :会在容器上下文中查找,和自己对象set方法后面的值对应的beanid。
autowire="byType"
byType :会在容器上下文中查找,和自己对象属性类型相同的bean。
-->
<bean id="people" class="cn.mao.pojo.People" p:name="maoshi" autowire="byType" />
</beans>
使用注解自动装配
使用注解装配需要在beans添加context约束,和在开启注解支持
然后在java类中使用注解
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"
xmlns:context="http://www.springframework.org/schema/context"
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:p="http://www.springframework.org/schema/p"
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"
xmlns:context="http://www.springframework.org/schema/context"
>
<!--开启注解的支持-->
<context:annotation-config/>
<bean id="cat" class="cn.mao.pojo.Cat"/>
<bean id="dog1" class="cn.mao.pojo.Dog"/>
<bean id="people" class="cn.mao.pojo.People" />
</beans>
在java中使用注解
public class People {
/*
* @Resource 与@Autowired 功能一样,但是前者自动同时通过name和数据类型去匹配,不过开发经常用的是@Autowired
* */
/*@Nullable 注解标记字段,说明这个字段可以为null*/
//@Autowired自动装配,通过name去匹配
//如果显示的定义了Autowired的required属性为false,说明这个属性对象可以为null,否则不允许为null
@Autowired(required = false)
private Cat cat;
// @Qualifier(value = "dog1") 自动装配环境复杂时候可以用它来指定一个bean的注入
@Qualifier(value = "dog1")
@Autowired
private Dog dog;
private String name;
//set get 省略......
}
获取java对象
@Test
public void people(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people", People.class);
people.getCat();
}