Spring高级装配之profile以及条件装配

profile
Primary
Qualifier
condition
@Profile、在xml中是Profile属性,作用是用于激活某些bean,比较常见的就是用于区分开发中的生产环境,测试环境等做区分。
如下是做代码区分的两组bean,也就是说下面两个bean你可以选择激活哪个部分,当然也可以同时激活。可以认为这两个bean中id为helloworld的bean在不同的环境下产生的作用是不同的。

xml形式

<beans profile="dev">
	<bean id="helloWorld" class="com.edu.class1">
	</bean>
</beans>

<beans profile="prod">
	<bean id="helloWorld" class="com.edu.class2">
	</bean>
</beans>

JavaConfig

@Configuration
public class class4 {
    @Profile("dev")
    @Bean(name = "helloWorld")
    public Object dev() {
        System.out.println("你好,dev");
        return null;
    }
    @Profile("prod")
    @Bean(name = "helloWorld")
    public Object prod() {
        System.out.println("你好,prod");
        return null;
    }
}

激活Profile的方式读取的参数是spring.profiles.active以及spring.profiles.default。这里说下两个优先级别,spring.profiles.active高于spring.profiles.default。
方式分为:

  1. dispacthServlet初始化参数
  2. web上下文参数
  3. JNDI条目
  4. 环境变量
  5. JVM系统属性
  6. 测试中用@ActiveProfiles

@Primary应用于优先级处理哪个bean,因为代码中可能会存在多个符合条件的bean可以自动注入,也就是说Spring不能帮你分辨哪个是符合你条件的bean进行自动注入的时候需要告诉Spring哪个bean是要优先于其他的bean的。下面的例子是两个bean同时是helloWorld,Spring肯定就晕了哪个是你要的呢。但是增加Primary后他就会有限使用dev这个bean了。

@Configuration
public class class4 {
	@Primary
    @Bean(name = "helloWorld")
    public Object dev() {
        System.out.println("你好,dev");
        return null;
    }
    
    @Bean(name = "helloWorld")
    public Object prod() {
        System.out.println("你好,prod");
        return null;
    }
}

@Qualifier是限定符限制bean所要接收的内容,通过id进行区分,如果一个接口有多个实现类时就会出现歧义,然后如果都是设置了Primary后也没办法进行优先设置时就需要用到这个了。以下代码的bean就会找到beanid为hello1的进行注入

@Configuration
public class class4 {

    @Bean(name = "hello1")
    public Object dev() {
        System.out.println("你好,dev");
        return new String("dev");
    }
    @Bean(name = "hello2")
    public Object hello2() {
        System.out.println("你好,prod");
        return new String("prod");
    }



    @Autowired
    @Qualifier("hello1")
    public Object test(Object hello) {
        System.out.println(hello.toString());
        return null;
    }
}

condition条件化bean就是通过一些条件判断是否生成bean,需要实现Condition接口。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值