Spring4---组件装配

本文详细介绍了Spring框架中如何通过@Autowired注解实现Bean的自动装配,包括在属性、构造器和setter方法上的应用,以及使用@Qualifier注解指定具体Bean的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 在配置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";
        }
    }

}

  • 测试获取EmpAction操作对象
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(){
        //获取控制层Bean
        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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值