Spring装配Bean(五)profile注解和解决自动注入的歧义性

本文详细介绍了Spring的profile功能,如何在Java配置和XML中定义profile,以及激活profile的方式。同时讨论了@Qualifier注解如何解决自动注入的歧义性,以及@Profile注解在条件化bean创建中的作用。最后提到了自定义限定符来进一步明确Bean的选择。
摘要由CSDN通过智能技术生成

配置profile bean

Spring为环境相关的bean所提供的解决方案其实和构建时候的方案没有太大区别,Spring会根据环境决定该创建那个bean和

不创建那个bean。

Spring的bean profile的功能。要使用profile,首先将所有不同的bean定义到一个或者多个profile之中,在将应用部署到每个环境中,要确保对应的profile处于激活(active)的状态

* Java配置中,使用@Profile注解指定某个bean属于那个profile

首先创建一个bean,用在开发环境和生产环境

@Configuration
@Profile("dev")
public class DevConfiguration {
	@Bean
	public HelloWorld helloWorld(){
		return new HelloWorld("dev environment .....");
	}
}
@Configuration
@Profile("prod")
public class ProductConfiguration {
	public HelloWorld helloWorld(){
		return new HelloWorld("product environment .... ");
	}
}

从Spring3.2开始,profile注解可以用在方法上,上面改为

@Configuration
public class HellloConfiguration {
	@Bean
	@Profile("dev")
	public HelloWorld devhelloWorld(){
		return new HelloWorld("dev environment .....");
	}
	@Bean
	@Profile("prod")
	public HelloWorld prodhelloWorld(){
		return new HelloWorld("product environment .....");
	}
}

只有规定的profile被激活,对应的bean才会被创建,没有指定profile的Bean始终都会创建

* XML中配置profile

* Beans标签使用profile属性表示当前的bean的profile

<?xml version="1.0" encoding="UTF-8"?>  
<beans profile="dev" xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   		xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd 
           ">  
  <bean id="helloWorld" class="com.erong.service.HelloWorld">
  	<property name="message" value="dev bean ....."></property>
  </bean>
</beans>  

需要注意的是

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值