原文地址: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. Windows server 2016 解决“无法完成域加入,原因是试图加入的域的SID与本计算机的SID相同。”

    使用克隆的系统时,加域是出现如下问题.“无法完成域加入,原因是试图加入的域的SID与本计算机的SID相同.” 问题原因:Windows使用SID来表示所有的安全对象(security principa ...

  2. NStimer 被堵塞

    我们在界面上滚动一个scrollview,那么我们会发如今停止滚动前,会发现NSTimer未被运行.就好像scrollView在滚动的时候将timer暂停了一样,在查看对应文档后发现,这事实上就是ru ...

  3. pat(A) 1065. A+B and C (64bit) (java大数)

    代码: import java.util.*; import java.math.*; public class Main { public static void main(String args[ ...

  4. The incident LOST_EVENTS occured on the master. Message: error writing to the binary log, Error_code

    1 mysq error日志报错例如以下: 2014-05-12 11:29:54 22977 [ERROR] Slave SQL: The incident LOST_EVENTS occured ...

  5. Use PSO to find minimum in OpenCASCADE

    Use PSO to find minimum in OpenCASCADE eryar@163.com Abstract. Starting from OCCT6.8.0 will include ...

  6. 43.可变参数实现printf

    #include <stdio.h> #include <stdio.h> #include <Windows.h> #include <stdarg.h&g ...

  7. Spark Tachyon编译部署(含单机和集群模式安装)

    Tachyon编译部署 编译Tachyon 单机部署Tachyon 集群模式部署Tachyon 1.Tachyon编译部署 Tachyon目前的最新发布版为0.7.1,其官方网址为http://tac ...

  8. 洛谷——P2093 零件分组

    https://www.luogu.org/problem/show?pid=2093 题目描述 某工厂生产一批棍状零件,每个零件都有一定的长度(Li)和重量(Wi).现在为了加工需要,要将它们分成若 ...

  9. 洛谷 P2782 友好城市

    P2782 友好城市 题目描述 有一条横贯东西的大河,河有笔直的南北两岸,岸上各有位置各不相同的N个城市.北岸的每个城市有且仅有一个友好城市在南岸,而且不同城市的友好城市不相同.每对友好城市都向政府申 ...

  10. 多线程编程(二)--进程&amp;&amp;线程

    看完上篇博文的介绍后,大家应该大概了解进程和线程的由来.有了这样一个背景我们进一步来看一下线程和进程. 引入进程: 进程能够提高系统的并发性.提高CPU的使用率,从而提高程序的性能.在曾经单道操作系统 ...