【译】Spring 4 @Profile注解示例
前言
译文链接:http://websystique.com/spring/spring-profile-example/
本文将探索Spring中的@Profile注解,可以实现不同环境(开发、测试、部署等)使用不同的配置。同样,除了使用注解也会给出基于XML配置的示例作为对比。
假设你有一个应用涉及数据库交互,你可能希望在开发环境上使用mysql数据库,在生产环境上使用oracle数据库,那么使用Spring的Profiles
,可以轻松达到这个目的,接下来我们将给出一个实例详细介绍这种情况。
涉及技术及开发工具
- Spring 4.0.6.RELEASE
- Maven 3
- JDK 1.6
- Eclipse JUNO Service Release 2
工程目录结构
步骤一:往pom.xml中添加依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.websystique.spring</groupId>
<artifactId>Spring4ProfilesExample</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging> <name>Spring4ProfilesExample</name> <properties>
<springframework.version>4.0.6.RELEASE</springframework.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency> </dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build> </project>
步骤二:创建Spring配置类
Spring配置类是指用@Configuration
注解标注的类,这些类包含了用@Bean
标注的方法。这些被@Bean
标注的方法可以生成bean并交由spring容器管理。
package com.websystique.spring.configuration; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan(basePackages = "com.websystique.spring")
public class AppConfig { @Autowired
public DataSource dataSource; }
以上配置只有一个属性被自动注入,接下来我们将展示这个dataSource属性可以根据不同的环境(开发环境或生产环境)注入不同的bean。
package com.websystique.spring.configuration; import javax.sql.DataSource; public interface DatabaseConfig { DataSource createDataSource(); }
一个简单的接口,可以被所有可能的环境配置实现
package com.websystique.spring.configuration; import javax.sql.DataSource; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.datasource.DriverManagerDataSource; @Profile("Development")
@Configuration
public class DevDatabaseConfig implements DatabaseConfig { @Override
@Bean
public DataSource createDataSource() {
System.out.println("Creating DEV database");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
/*
* Set MySQL specific properties for Development Environment
*/
return dataSource;
} }
package com.websystique.spring.configuration; import javax.sql.DataSource; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.datasource.DriverManagerDataSource; @Profile("Production")
@Configuration
public class ProductionDatabaseConfig implements DatabaseConfig { @Override
@Bean
public DataSource createDataSource() {
System.out.println("Creating Production database");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
/*
* Set ORACLE specific properties for Production environment
*/
return dataSource;
} }
以上两个配置类都实现了DatabaseConfig接口,特殊的地方在于它们都用@Profile
标注。
被@Profile
标注的组件只有当指定profile值匹配时才生效。
可以通过以下方式设置profile值:
1、设置spring.profiles.active
属性(通过JVM参数、环境变量或者web.xml中的Servlet context参数)
2、ApplicationContext.getEnvironment().setActiveProfiles(“ProfileName”)
根据你的实际环境设置profile值,然后被profile标注(而且value=设置值)的bean才会被注册到spring容器。
步骤三:运行main方法测试
package com.websystique.spring; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class AppMain { public static void main(String args[]){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//Sets the active profiles
context.getEnvironment().setActiveProfiles("Development");
//Scans the mentioned package[s] and register all the @Component available to Spring
context.scan("com.websystique.spring");
context.refresh();
context.close();
} }
注意以上代码,context.scan(
"com.websystique.spring"
)
扫描到该包并开始注册所有被@Component标注的bean时,如果同时遇到被@Profile注解标注的bean时,会与profile值做比较,profile值匹配则注册到spring容器,否则直接跳过。
在我们这个例子中,DevDatabaseConfig会被注册到Spring容器中。
运行以上程序,结果如下:
Creating DEV database
附:基于XML的配置
替换DevelopmentDatabaseConfig配置为dev-config-context.xml (src/main/resources/dev-config-context.xml
)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/websystique" />
<property name="username" value="myuser" />
<property name="password" value="mypassword" />
</bean> </beans>
替换ProductionDatabaseConfig配置为prod-config-context.xml (src/main/resources/prod-config-context.xml
)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value=" oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@PRODHOST:PRODPORT/websystique" />
<property name="username" value="myproduser" />
<property name="password" value="myprodpassword" />
</bean> </beans>
替换AppConfig配置为app-config.xml (src/main/resources/app-config.xml
)
<?xml version="1.0" encoding="UTF-8"?>
<beans 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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.websystique.spring"/> <beans profile="Development">
<import resource="dev-config-context.xml"/>
</beans> <beans profile="Production">
<import resource="prod-config-context.xml"/>
</beans> </beans>
根据实际的profile配置,相应的config-context.xml文件会被加载,其它的会被忽略。
最后,main方法如下:
package com.websystique.spring; import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class AppMain { public static void main(String args[]){
AbstractApplicationContext context = new ClassPathXmlApplicationContext("app-config.xml");
//Sets the active profiles
context.getEnvironment().setActiveProfiles("Development");
/*
* Perform any logic here
*/
context.close();
} }
运行程序,会得到相同的结果。
程序源码
http://websystique.com/?smd_process_download=1&download_id=799
【译】Spring 4 @Profile注解示例的更多相关文章
- 十、Spring的@Profile注解
首先我们来看看spring官方文档对这个注解的解释: The @Profile annotation allows you to indicate that a component is eligib ...
- 【转】Spring Boot Profile使用
http://blog.csdn.net/he90227/article/details/52981747 摘要: spring Boot使用@Profile注解可以实现不同环境下配置参数的切换,任何 ...
- 【译】Spring 4 @PropertySource和@Value注解示例
前言 译文链接:http://websystique.com/spring/spring-propertysource-value-annotations-example/ 本篇文章将展示如何通过@P ...
- spring切换环境变量——@Profile注解的使用
在容器中如果存在同一类型的多个组件,也可以使用@Profile注解标识要获取的是哪一个bean,这在不同的环境使用不同的变量的情景特别有用.例如,开发环境.测试环境.生产环境使用不同的数据源,在不改变 ...
- 使用 spring.profiles.active 及 @profile 注解 动态化配置内部及外部配置
引言:使用 spring.profiles.active 参数,搭配@Profile注解,可以实现不同环境下(开发.测试.生产)配置参数的切换 一.根据springboot的配置文件命名约定,结合ac ...
- spring boot: 一般注入说明(四) Profile配置,Environment环境配置 @Profile注解
1.通过设定Environment的ActiveProfile来设置当前context所需要的环境配置,在开发中使用@Profile注解类或方法,达到不同情况下选择实例化不同的Bean. 2.使用jv ...
- 【Spring Cloud】Spring Cloud之自定义@SpringCloudProfile注解实现@Profile注解的功能
一.为什么会想到定义@SpringCloudProfile这样的注解 首页提一下@Profile注解:它主要用与Spring Boot多环境配置中,指定某个类只在指定环境中生效,比如swagger的配 ...
- 【Spring】使用@Profile注解实现开发、测试和生产环境的配置和切换,看完这篇我彻底会了!!
写在前面 在实际的企业开发环境中,往往都会将环境分为:开发环境.测试环境和生产环境,而每个环境基本上都是互相隔离的,也就是说,开发环境.测试环境和生产环境是互不相通的.在以前的开发过程中,如果开发人员 ...
- 【Spring】简单的Spring AOP注解示例
引入相关包: <properties> <spring.version>3.0.5.RELEASE</spring.version> <aspectj.ver ...
随机推荐
- 使用mapreduce计算环比的实例
最近做了一个小的mapreduce程序,主要目的是计算环比值最高的前5名,本来打算使用spark计算,可是本人目前spark还只是简单看了下,因此就先改用mapreduce计算了,今天和大家分享下这个 ...
- CSharpGL(39)GLSL光照示例:鼠标拖动太阳(光源)观察平行光的漫反射和镜面反射效果
CSharpGL(39)GLSL光照示例:鼠标拖动太阳(光源)观察平行光的漫反射和镜面反射效果 开始 一图抵千言.首先来看鼠标拖动太阳(光源)的情形. 然后是鼠标拖拽旋转模型的情形. 然后我们移动摄像 ...
- TSQL 分组集(Grouping Sets)
分组集(Grouping Sets)是多个分组的并集,用于在一个查询中,按照不同的分组列对集合进行聚合运算,等价于对单个分组使用“union all”,计算多个结果集的并集.使用分组集的聚合查询,返回 ...
- 【.net 深呼吸】使用二进制格式来压缩XML文档
在相当多的情况下,咱们写入XML文件默认是使用文本格式来写入的,如果XML内容是通过网络传输,或者希望节省空间,特别是对于XML文档较大的情况,是得考虑尽可能地压缩XML文件的大小. XmlDicti ...
- 版本控制工具比较-CVS,SVN,GIT
首先介绍几个版本控制软件相互比较的重要依据: a.版本库模型(Repository model):描述了多个源码版本库副本间的关系,有客户端/服务器和分布式两种模式.在客户端/服务器模式下,每一用户通 ...
- 创建SSH Key连接github或gitlab
mac下用SoureceTree下载github或gitlab上的项目时,需要进行ssh key验证.每次重装系统啥的都要重新弄,我在csdn上看到一篇不错的文章.转载一下,以后自己找起来也方便. 地 ...
- DropDownList 下拉框选择改变,促发事件和防全局刷新(记录)
代码: <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:Script ...
- ES6笔记(5)-- Generator生成器函数
系列文章 -- ES6笔记系列 接触过Ajax请求的会遇到过异步调用的问题,为了保证调用顺序的正确性,一般我们会在回调函数中调用,也有用到一些新的解决方案如Promise相关的技术. 在异步编程中,还 ...
- jquery获取dropdownlist的value和text值
1.jquery //获取value值 $("#ddlSubmodel").val(); //获取text值 $("#ddlSubmodel").find(&q ...
- C#开发微信门户及应用(12)-使用语音处理
我们知道,微信最开始就是做语音聊天而使得其更加流行的,因此语音的识别处理自然也就成为微信交流的一个重要途径,微信的开发接口,也提供了对语音的消息请求处理.本文主要介绍如何利用语音的识别,对C#开发的微 ...