- 在配置Bean的时候,Bean和Bean之间往往存在有依赖关系,一个Bean中往往包含其它Bean类型的属性.
- 可以通过注解的方式让IOC容器自动装配这些属性.
- 在使用注解的时候,使用<context:component-scan>标签配置扫描基包,还会自动进行以下操作.

使用 @Autowired 自动装配 Bean

使用示例
- 在软件分成设计中,在控制层往往需要一个服务层的操作对象,此时就可以使用"@Autowired"注解自动装配属性.
- 前提是有配置对应类型的Bean
@Controller
public class EmpAction {
@Autowired
private EmployeeService employeeService;
public String add(){
if(employeeService.add(new Employee())){
return "add_list.jsp";
}else{
return "error.jsp";
}
}
}
package mao.shu.spring.annotation;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
public class EmpActionTest {
private ApplicationContext app;
@Before
public void before(){
this.app = new ClassPathXmlApplicationContext("mao/shu/spring/annotation/annotation.xml");
}
@Test
public void test(){
EmpAction empAction = this.app.getBean("empAction",EmpAction.class);
System.out.println(empAction.add());
}
}

- 除了使用在属性上之外,还可以使用在构造器或者setter()方法上
@Autowired
public EmpAction(EmployeeService employeeService) {
this.employeeService = employeeService;
}
- 如果出现多个类型相匹配的情况下,先会自动找到名称相匹配的Bean,使用注解配置的Bean都有一个默认的名称,就是类名称小写的形式.
- 例如上述例子中属性类型为"EmployeeService",那么默认会寻找"employeeService"的Bean来装配,如果找不到默认名称,则会抛出异常,
- 如果要制定匹配的名称可以使用"@Qualifier "注解
@Autowired
@Qualifier("empservice")
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
@Autowired
public void setEmployeeService(@Qualifier("empservice") EmployeeService employeeService) {
this.employeeService = employeeService;
}
使用 @Resource 或 @Inject 自动装配 Bean
