【译】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 ...
随机推荐
- [异常解决] ubuntukylin16.04 LTS中关于flash安装和使用不了的问题解决
http://www.linuxdiyf.com/linux/25211.html 归纳解决flash插件大法: 启动器中找到 软件更新,启动,点击 其它软件,把Canonical合作伙伴前方框 选上 ...
- JavaScript继承的模拟实现
我们都知道,在JavaScript中只能模拟实现OO中的"类",也就意味着,在JavaScript中没有类的继承.我们也只能通过在原对象里添加或改写属性来模拟实现. 先定义一个父类 ...
- 关于apue.3e中apue.h的使用
关于apue.3e中apue.h的使用 近来要学一遍APUE第三版,并于此开博做为记录. 先下载源文件: # url: http://http//www.apuebook.com/code3e.htm ...
- Java——搭建自己的RESTful API服务器(SpringBoot、Groovy)
这又是一篇JavaWeb相关的博客,内容涉及: SpringBoot:微框架,提供快速构建服务的功能 SpringMVC:Struts的替代者 MyBatis:数据库操作库 Groovy:能与Java ...
- JS事件调试 - 查找HTML元素绑定的事件以及绑定代码所在位置
日常的网页开发调试工作中,经常需要知道指定的某个网页元素绑定了哪些事件以及绑定代码的位置,下面介绍三种用来跟踪页面中的事件的方法. 1.使用firefox调试 我们可以使用firefox的debug工 ...
- ng-directive-选择数据
本文是用angularjs指令写的一个简易数据选择功能,其实就是两个下拉框,把两边的数据相互交换而已,这样的功能最早应该是用jquery写过,但移动端js框架angularjs如果还嵌套jquery来 ...
- linq to js使用汇总
用途:方便js操作查询json数据. 下载网址:http://jslinq.codeplex.com/ 使用方法:只需要引用linq.js即可. 查询方法: 一.where查询 var myList ...
- 使用webfont为easyui扩充图标
目前回到pc端开发,开始用了easyui这个框架.重拾easyui后感觉这个框架用的很多技术太古老,页面风格也太控件化.单从图标一项来说吧,这种花花绿绿的图标用户一看都傻了眼,同时整个框架就提供了那么 ...
- OSGi 基本原理
定义 OSGi(Open Service Gateway Initiative)技术是面向Java的动态模型系统. 这个框架实现了一个优雅.完整和动态地组价模型.应用程序(称为bundle)无序重新引 ...
- 设计模式(十三)代理模式(Proxy Pattern)
一.引言 在软件开发过程中,有些对象有时候会由于网络或其他的障碍,以至于不能够或者不能直接访问到这些对象,如果直接访问对象给系统带来不必要的复杂性,这时候可以在客户端和目标对象之间增加一层中间层,让代 ...