原文地址:http://www.mkyong.com/spring/spring-profiles-example/

Spring @Profile allow developers to register beans by condition. For example, register beans based on what operating system (Windows, *nix) your application is running, or load a database properties file based on the application running in development, test, staging or production environment.

In this tutorial, we will show you a Spring @Profile application, which does the following stuff :

  1. Create two profiles – dev and live
  2. If profile “dev” is enabled, return a simple cache manager – ConcurrentMapCacheManager
  3. If profile “live” is enabled, return an advanced cache manager – EhCacheCacheManager
Note

  1. Spring has supported @Profile annotation since version 3.1
  2. @Profile is inside spring-context.jar

Tools used :

  1. Spring 4.1.4.RELEASE
  2. Ehcache 2.9.0
  3. JDK 1.7

1. Spring @Profile Examples

This @Profile annotation can be applied at class level or method level.

1.1 Normal Spring Configuration, enable caching, so that Spring will expect a cache manager at runtime.

AppConfig
package com.mkyong.test;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@EnableCaching
@ComponentScan({ "com.mkyong.*" })
public class AppConfig {
}

1.2 A dev profile, which returns a simple cache manager concurrentMapCacheManager

CacheConfigDev.java
package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; @Configuration
@Profile("dev")
public class CacheConfigDev { private static final Logger log = LoggerFactory.getLogger(CacheConfigDev.class); @Bean
public CacheManager concurrentMapCacheManager() {
log.debug("Cache manager is concurrentMapCacheManager");
return new ConcurrentMapCacheManager("movieFindCache");
} }

1.3 A live profile, which returns ehCacheCacheManager

CacheConfigLive.java
package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource; @Configuration
@Profile("live")
public class CacheConfigLive { private static final Logger log = LoggerFactory.getLogger(CacheConfigDev.class); @Bean
public CacheManager cacheManager() {
log.debug("Cache manager is ehCacheCacheManager");
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
} @Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
cmfb.setShared(true);
return cmfb;
} }
 

2. Enable @Profile

Few code snippets to show you how to enable a Spring profile.

2.1 For non-web application, you can enable a profile via the Spring context environment.

App.java
package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class App { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//Enable a "live" profile
context.getEnvironment().setActiveProfiles("live");
context.register(AppConfig.class);
context.refresh(); ((ConfigurableApplicationContext) context).close(); }
}

Output

DEBUG com.mkyong.test.CacheConfigDev - Cache manager is ehCacheCacheManager

Or, via the system property like this

App.java
package com.mkyong.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.AbstractEnvironment; public class App { public static void main(String[] args) { //Enable a "dev" profile
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); }
}

Output

DEBUG com.mkyong.test.CacheConfigDev - Cache manager is concurrentMapCacheManager

2.2 For web application, defined a context parameter in web.xml

web.xml
	<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>live</param-value>
</context-param>

2.3 For web application don’t have web.xml, like servlet 3.0+ container

MyWebInitializer.java
package com.mkyong.servlet3;

import javax.servlet.ServletContext;
import javax.servlet.ServletException; public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer { //...
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.setInitParameter("spring.profiles.active", "live");
} }

2.4 For Unit Test, uses @ActiveProfiles

CacheManagerTest.java
package com.mkyong.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.cache.CacheManager; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class })
@ActiveProfiles("dev")
public class CacheManagerTest { @Autowired
private CacheManager cacheManager; @Test
public void test_abc() {
//...
} }
 

3. More…

3.1 Spring @Profile can apply at method level.

AppConfig.java
package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource; @Configuration
@EnableCaching
@ComponentScan({ "com.mkyong.*" })
public class AppConfig { private static final Logger log = LoggerFactory.getLogger(AppConfig.class); @Bean
@Profile("dev")
public CacheManager concurrentMapCacheManager() {
log.debug("Cache manager is concurrentMapCacheManager");
return new ConcurrentMapCacheManager("movieFindCache");
} @Bean
@Profile("live")
public CacheManager cacheManager() {
log.debug("Cache manager is ehCacheCacheManager");
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
} @Bean
@Profile("live")
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
cmfb.setShared(true);
return cmfb;
} }

3.2 You can enable multiple profiles.

	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("live", "linux");
//or
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev, windows");
web.xml
	<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>stage, postgresql</param-value>
</context-param>
	@ActiveProfiles({"dev", "mysql","integration"})
        ((ConfigurableEnvironment)context.getEnvironment())
.setActiveProfiles(new String[]{"dev", "embedded"});

Spring Profiles example--转载的更多相关文章

  1. springboot中spring.profiles.include

    springboot中spring.profiles.include的妙用. 我们有这样的一个springboot项目.项目分为开发.测试.生产三个不同阶段(环境),每个阶段都会有db.ftp.red ...

  2. 使用 spring.profiles.active 及 @profile 注解 动态化配置内部及外部配置

    引言:使用 spring.profiles.active 参数,搭配@Profile注解,可以实现不同环境下(开发.测试.生产)配置参数的切换 一.根据springboot的配置文件命名约定,结合ac ...

  3. SpringBoot application.yml logback.xml,多环境配置,支持 java -jar --spring.profiles.active

    趁今天有时间整理了一下 启动命令为 //开发环境 java -jar app.jar --spring.profiles.active=dev--server.port=8060 //测试环境 jav ...

  4. spring程序打包war,直接通过-jar启动,并指定spring.profiles.active参数控制多环境配置

    备注:spring boot有内嵌tomcat,jar项目可以用java -jar命令启动,war包也可以,且可以直接指定spring.profiles.active参数控制多环境配置 直接指定传参, ...

  5. springboot中spring.profiles.active来引入多个properties文件 & Springboot获取容器中对象

    1.    引入多个properties文件 很多时候,我们项目在开发环境和生成环境的环境配置是不一样的,例如,数据库配置,在开发的时候,我们一般用测试数据库,而在生产环境的时候,我们是用正式的数据, ...

  6. Spring.profiles多环境配置最佳实践

    转自:https://www.cnblogs.com/jason0529/p/6567373.html Spring的profiles机制,是应对多环境下面的一个解决方案,比较常见的是开发和测试环境的 ...

  7. spring boot 入门 使用spring.profiles.active来分区配置

    很多时候,我们项目在开发环境和生成环境的环境配置是不一样的,例如,数据库配置,在开发的时候,我们一般用测试数据库,而在生产环境的时候,我们是用正式的数据,这时候,我们可以利用profile在不同的环境 ...

  8. spring-boot:run启动时,指定spring.profiles.active

    Maven启动指定Profile通过-P,如mvn spring-boot:run -Ptest,但这是Maven的Profile. 如果要指定spring-boot的spring.profiles. ...

  9. SpringBoot application.yml logback.xml,多环境配置,支持 java -jar --spring.profiles.active(转)

    趁今天有时间整理了一下 启动命令为 //开发环境 java -jar app.jar --spring.profiles.active=dev--server.port=8060 //测试环境 jav ...

随机推荐

  1. lsblk---列出所有可用块设备的信息,

    lsblk命令用于列出所有可用块设备的信息,而且还能显示他们之间的依赖关系,但是它不会列出RAM盘的信息.块设备有硬盘,闪存盘,cd-ROM等等.lsblk命令包含在util-linux-ng包中,现 ...

  2. iOS 热门高效开源库集锦,收藏备用

    一.推荐使用的第三方库 1:基于响应式编程思想的ReactiveCocoa 地址:https://github.com/ReactiveCocoa/ReactiveCocoa 2:iOS解耦与组件化开 ...

  3. 【Henu ACM Round#16 B】 Bear and Colors

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] O(n^2)枚举每一个区间. 然后维护这个区间里面的"统治数字"是什么. 对于每个区间cnt[统治数字]++; ...

  4. 基于TI Davinci架构的多核/双核开发高速扫盲(以OMAP L138为例),dm8168多核开发參考以及达芬奇系列资料user guide整理

    基于TI Davinci架构的双核嵌入式应用处理器OMAPL138开发入门 原文转自http://blog.csdn.net/wangpengqi/article/details/8115614 感谢 ...

  5. adb-端口被占用解决办法(win)

    今天在window下使用adb的时候,提示我说5037端口被占用. * daemon not running. starting it now on port * ADB server didn't ...

  6. 关于cook操作

    http://www.cnblogs.com/fishtreeyu/archive/2011/10/06/2200280.html

  7. 【DRF视图】

    目录 开始使用内置视图 请结合[DRF序列化]此文献中的数据文件及序列化文件来阅读如下代码. DRF视图为我们提供了非常简便的方法--内置了增删改查等一系列的操作. 我们只需在url中指定对应的方法, ...

  8. ip---查看网络信息

    Linux的ip命令和ifconfig类似,但前者功能更强大,并旨在取代后者. ifconfig属于net-tools.ip属于iproute2 设置一个IP地址,可以使用下列ip命令: ip add ...

  9. Windows学习总结(3)——成为电脑高手必备的cmd命令大全

    曾经看电影和电视里面电脑黑客快速敲击电脑键盘,一行行命令在电脑屏幕闪过,一个回车过后,一排排英文象走马灯一样在屏幕上转瞬即逝,那才是我们梦寐以求的高手,有木有!实际上,不光是黑客和系统维护人员,一般的 ...

  10. 重构insert update 比较两个datatbale

    #region 下载时重构insert(数据带null处理) public void DownDataInsert(DataTable _dt, string TableName,DBHelper d ...