Spring IOC @Autowired、@Qualifier 、@Primary 注解说明

 

1.@Autowired

依赖注入的注解

2.@Primary

官网文档的解释:

对应的翻译,来自搜狗(凑合可以看懂)

代码示例:

个人理解:在通过javaconfig进行声明bean时,加上该注解后,那个bean时首要选择。

3.@Qualifier

标识符,因为@Autowired默认时按照bean的类型注入(bytype),当别注入的接口有多个实现时,如果不加以区分,程序将会出现异常,使用@Qualifier进行标识来解决这个问题

 

示例:

声明的bean

package com.lhj.service;

public interface UserService {

    void eat();
}


-------------------------------------------------------------

package com.lhj.service.impl;

import com.lhj.service.UserService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    public void eat() {
        System.out.println("UserServiceImpl");
    }
}

-------------------------------------------------------------
package com.lhj.service.impl;

import com.lhj.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceExtendImpl implements UserService {
    public void eat() {
        System.out.println("UserServiceExtendImpl");
    }
}

注入并使用bean 

package com.lhj.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class UserDemoService {

    @Autowired
    @Qualifier("userServiceExtendImpl")
    private UserService userService;
}

添加@Qualifier来区分这里的UserServiceImpl 和UserServiceExtendImpl 两个bean ,@Qualifier括号内的值可以是bean的id或name值

官网文档说明:

 

搜狗翻译

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值