springboot配置类获取同类中的bean几种方式

一,在方法参数中使用@Qualifier

在创建A对象时,需要用到B对象,可以在方法的参数中使用@Qualifier("beanName")的方式注入;

注意:beanName 必须指定,且两个必须一致,否则编译不通过

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class MyConfig {
    @Bean
    public A getA(@Qualifier("b") B b){
        A a = new A();
        System.out.println("getA方法中的b="+b);
        a.setB(b);
        return a;
    }

    @Bean("b")
    public B getB(){
        B b =new B();
        System.out.println("getB方法中的b="+b);
        return b;
    }

}

可以看到两个B对象的内存地址一样

二,直接调用的方式

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class MyConfig {

    @Bean
    public A getA(){
        A a = new A();
        B b =getB();//直接调用得到对象
        System.out.println("getA方法中的b="+b);
        a.setB(b);
        return a;
    }

    @Bean("b")
    public B getB(){
        B b =new B();
        System.out.println("getB方法中的b="+b);
        return b;
    }

}

这种方式我一直以为会产生两个B对象,但实际上spring做了处理,只会产生一个对象,结果如下:

这是为啥呢?

这就说到了@Configuration配置类的full和lite模式,具体看@Configuration配置类的full和lite模式_不惧不惑的博客-优快云博客_full模式

三,定义成员变量进行注入

把B定义成了一个成员变量,使用@Resource给其注入值(@Autowired也可以)

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class MyConfig {
    @Resource
    private B b;

    @Bean
    public A getA(){
        A a = new A();
        System.out.println("成员变量中的b="+b);
        a.setB(b);
        return a;
    }

    @Bean("b")
    public B getB(){
        B b =new B();
        System.out.println("getB方法中的b="+b);
        return b;
    }

}

 

总结:

方式一、方式三都可以跨类使用,方式二只适合本类中使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值