1、修改 PresonServiceImpl 类,代码如下:
![]()
package com.learn.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import com.learn.dao.PresonDao;
import com.learn.service.PresonService;
/**
* 业务层
* @author Administrator
*
*/
public class PresonServiceImpl implements PresonService {
@Autowired private PresonDao presonDao;
public PresonServiceImpl(){
}
public void setPresonDao(PresonDao presonDao) {
this.presonDao = presonDao;
}
/* (non-Javadoc)
* @see com.learn.service.impl.PresonService#save()
*/
@Override
public void save(){
presonDao.add();
}
}
在前面学习中知道 @Autowired 默认按类型装配,在xml 文件中会找到与 PresonDao 该类型匹配的 bean ,然后将 找到的 bean 注入到 presonDao 中。
2、单元测试类,代码如下:
![]()
package junit.test;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.learn.service.PresonService;
public class TestSpring {
@Test
public void initContainerSpring() {
//实例化spring容器 (使用类构造器实例化)
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("com//learn//spring//learn1.xml");
PresonService personService = (PresonService)ctx.getBean("personService");
personService.save();
}
}
3、XML 文件不变,与之前的一样。
4、如果我们想使用按名称装配,可以结合@Qualifier注解一起使用,代码如下:
@Autowired @Qualifier("personDao1")
private PresonDao presonDao;
不再做具体的测试。
5、@Autowired注解,它有个 required 属性,默认情况下该属性值为 true ,即 @Autowired(required=true),表示依赖对象必须存在;如果允许null值,可以设置它required属性为false。
6、自动装配依赖对象:
<bean id="..." class="..." autowire="byType"/>
autowire属性取值如下:
byType:按类型装配,可以根据属性的类型,在容器中寻找跟该类型匹配的bean。如果发现多个,那么将会抛出异常。如果没有找到,即属性值为null。
byName:按名称装配,可以根据属性的名称,在容器中寻找跟该属性名相同的bean,如果没有找到,即属性值为null。
constructor与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean,那么将会抛出异常。
autodetect:通过bean类的自省机制(introspection)来决定是使用constructor还是byType方式进行自动装配。如果发现默认的构造器,那么将使用byType方式。