前言

译文链接: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注解示例的更多相关文章

  1. 十、Spring的@Profile注解

    首先我们来看看spring官方文档对这个注解的解释: The @Profile annotation allows you to indicate that a component is eligib ...

  2. 【转】Spring Boot Profile使用

    http://blog.csdn.net/he90227/article/details/52981747 摘要: spring Boot使用@Profile注解可以实现不同环境下配置参数的切换,任何 ...

  3. 【译】Spring 4 @PropertySource和@Value注解示例

    前言 译文链接:http://websystique.com/spring/spring-propertysource-value-annotations-example/ 本篇文章将展示如何通过@P ...

  4. spring切换环境变量——@Profile注解的使用

    在容器中如果存在同一类型的多个组件,也可以使用@Profile注解标识要获取的是哪一个bean,这在不同的环境使用不同的变量的情景特别有用.例如,开发环境.测试环境.生产环境使用不同的数据源,在不改变 ...

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

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

  6. spring boot: 一般注入说明(四) Profile配置,Environment环境配置 @Profile注解

    1.通过设定Environment的ActiveProfile来设置当前context所需要的环境配置,在开发中使用@Profile注解类或方法,达到不同情况下选择实例化不同的Bean. 2.使用jv ...

  7. 【Spring Cloud】Spring Cloud之自定义@SpringCloudProfile注解实现@Profile注解的功能

    一.为什么会想到定义@SpringCloudProfile这样的注解 首页提一下@Profile注解:它主要用与Spring Boot多环境配置中,指定某个类只在指定环境中生效,比如swagger的配 ...

  8. 【Spring】使用@Profile注解实现开发、测试和生产环境的配置和切换,看完这篇我彻底会了!!

    写在前面 在实际的企业开发环境中,往往都会将环境分为:开发环境.测试环境和生产环境,而每个环境基本上都是互相隔离的,也就是说,开发环境.测试环境和生产环境是互不相通的.在以前的开发过程中,如果开发人员 ...

  9. 【Spring】简单的Spring AOP注解示例

    引入相关包: <properties> <spring.version>3.0.5.RELEASE</spring.version> <aspectj.ver ...

随机推荐

  1. 导入 cocoapods引入的第三方库头文件,提示找不到

    解决办法: 1,Build Settings ->Header Search Paths 2, 双击 Header Search Paths  添加一个, $(PODS_ROOT), 选择项选: ...

  2. 百度API ; 很多有用的接口及公用 数据

    百度API : http://apistore.baidu.com/ . 比如手机号码:

  3. Maven中安装本地Jar包到仓库中或将本地jar包上传

    摘要 maven install 本地jar 命令格式 mvn install:install-file -DgroupId=<group_name> -DartifactId=<a ...

  4. 设计模式(十一):从文Finder中认识"组合模式"(Composite Pattern)

    上一篇博客中我们从从电影院中认识了"迭代器模式"(Iterator Pattern),今天我们就从文件系统中来认识一下“组合模式”(Composite Pattern).说到组合模 ...

  5. Core Java 总结(异常类问题)

    所有代码均在本地编译运行测试,环境为 Windows7 32位机器 + eclipse Mars.2 Release (4.5.2) 2016-10-17 整理 下面的代码输出结果是多少?为什么?并由 ...

  6. 全球PM25实时可视化

    星期一的早上,我在办公区鸟瞰窗外,目光所到之处,用顾城的那首"你看天时很近,看我时很远"倒是格外的应景.作为一名父亲,看着工位上3M的口罩,想想此刻还在熟睡的孩子,多少有些无奈-- ...

  7. DotNet程序配置文件

    在实际的项目开发中,对于项目的相关信息的配置较多,在.NET项目中,我们较多的将程序的相关配置直接存储的.config文件中,例如web.config和app.config. .NET中配置文件分为两 ...

  8. python中的str,unicode和gb2312

    实例1: v1=u '好神奇的问题!?' type(v1)->unicode v1.decode("utf-8")# not work,because v1 is unico ...

  9. 从.NET和Java之争谈IT这个行业

    一.有些事情难以回头 开篇我得表名自己的立场:.NET JAVA同时使用者,但更加偏爱.NET.原因很简单 1.NET语言更具开放性,从开源协议和规范可以看出; 2.语言更具优势严谨; 3.开发工具V ...

  10. Rafy 框架 - 使用 SqlTree 查询

    本文介绍如何使用 Rafy 框架中的 Sql Tree 查询: 除了开发者常用的 Linq 查询,Rafy 框架还提供了 Sql 语法树的方式来进行查询. 这种查询方式下,开发者不需要直接编写真正的 ...