为何需要@Autowired注入,以及@Autowired注释的作用

本文深入解析了Spring框架中@Autowired注释的使用原理及其在解决Bean依赖注入问题中的作用。阐述了当Spring容器中存在多个候选Bean时,如何利用@Qualifier注释指定具体注入的Bean,避免BeanCreationException异常。

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

为何需要@Autowired注入,以及@Autowired注释的作用

spring可以自动帮你把Bean里面引用的对象的setter/getter方法省略,它会自动帮你set/get(其实是通过反射技术实现的)。
@Autowired注释进行自动注入时,spring容器中匹配的候选Bean数目必须有且仅有一个。
当找不到一个匹配的Bean时,spring容器将抛出BeanCreationException异常,并指出必须至少拥有一个匹配的Bean。
如果spring容器中拥有多个候选Bean,spring容器在启动时也会抛出BeanCreationException
这个时候就可以借助@Qualifier注释指定注入Bean的名称,这样@Autowired遇到多个候选Bean的问题也就解决了。

以上内容参考:https://blog.youkuaiyun.com/STUDENTstudent123/article/details/86774033

下面通过代码进行解释说明:

/*很多人疑惑,为什么需要注入Customer,因为下面的语句需要用到。
  service层通过调用CustomerMapper的对象,进而调用addCustomer方法
  因为CustomerMapper类里面有很多方法,我们进行数据库操作室往往只需要操作部分方法,
  所以,通过service层进行操作,CustomerMapper里面的具体方法*/

package com.sm.service;

import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sm.mapper.CustomerMapper;
import com.sm.po.Customer;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
	// 注解注入CustomerMapper
	@Autowired
	private CustomerMapper customerMapper;

	public void addCustomer(Customer customer) {
/*很多人疑惑,为什么需要注入Customer,因为下面的语句需要用到。
  service层通过调用CustomerMapper的对象,进而调用addCustomer方法
  因为CustomerMapper类里面有很多方法,我们进行数据库操作室往往只需要操作部分方法,
  所以,通过service层进行操作,CustomerMapper里面的具体方法*/
		this.customerMapper.addCustomer(customer);
		int i = 1/0;
	}
}

欢迎吐槽!!!

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值