spring注入bean的方式

1.首先了解注入对象注解

1.1 @Autowired 注解 & @Resource 注解
1.1.1 Autowired 和 Resource的区别:
/**
 * Autowired是spring注解,默认会根据byType的方式自动注入bean,如果需要使用byName的方式需要配合@Qualifier注解使用
 * Autowired注解支持三种注入方式,属性注入、构造函数、set注入
 * Resource是Java的注解,默认会根据byName的方式自动注入bean,byName无法找到对应的bean会根据byType的方式
 * Resource注解支持两种注入方式,属性注入、set注入
 */
1.1.2 @Autowired的三种注入方式

属性注入

// 属性注入,spring5.0之后不建议直接注入,会产生警告“Field injection is not recommended”
//spring 官方文档推荐 构造函数注入和set注入
@Autowired //属性注入
private AutowiredServiceA autowiredService;

构造函数注入

private final AutowiredInterface autowiredServiceA;
// 构造方法注入 注入
// @Autowired spring4.5之后这个注解可以忽略不写
private AutowiredTest(AutowiredInterface autowiredServiceA) {
    this.autowiredServiceA = autowiredServiceA;
}

set注入

private AutowiredInterface autowiredServiceA;

   @Autowired // set注入需要加上@Autowired注解,否则 null指针
   public void setAutowiredServiceA(AutowiredInterface autowiredServiceA) {
       this.autowiredServiceA = autowiredServiceA;
   }

注: 如果一个接口下有多个实现类,进行注入的时候,需要用@Qualifier注解
比如:

public interface AutowiredInterface {
    String getName();
}

@Service
@Qualifier("AutowiredServiceA") // 用@Qualifier指定名称
public class AutowiredServiceA implements AutowiredInterface{

    public String getName(){
        return "AutowiredServiceA";
    }
}

@Service
@Qualifier("AutowiredServiceB") // 用@Qualifier指定名称
public class AutowiredServiceB implements AutowiredInterface{
    @Override
    public String getName() {
        return "AutowiredServiceB";
    }
}


// 注入
private AutowiredInterface autowiredServiceA;

   @Autowired // set注入需要加上@Autowired注解,否则 null指针
   public void setAutowiredServiceA(@Qualifier("AutowiredServiceA") AutowiredInterface autowiredServiceA) {
       this.autowiredServiceA = autowiredServiceA;
   }
1.1.3 @Resource的两种注入方式

属性注入

// 如果多个实现类,可以根据实现类的类名首字母小写进行注入
@Resource
private AutowiredInterface autowiredServiceA;

set注入

private AutowiredInterface autowiredServiceB;

    @Resource
    public void setAutowiredServiceB(AutowiredInterface autowiredServiceB) {
        this.autowiredServiceB = autowiredServiceB;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值