【译】Spring 4 @Profile注解示例

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介:

本文将探索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://www.cnblogs.com/chenpi/p/6213849.html,如需转载请自行联系原作者
相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
1月前
|
Java 开发者 Spring
【SpringBoot 异步魔法】@Async 注解:揭秘 SpringBoot 中异步方法的终极奥秘!
【8月更文挑战第25天】异步编程对于提升软件应用的性能至关重要,尤其是在高并发环境下。Spring Boot 通过 `@Async` 注解简化了异步方法的实现。本文详细介绍了 `@Async` 的基本用法及配置步骤,并提供了示例代码展示如何在 Spring Boot 项目中创建与管理异步任务,包括自定义线程池、使用 `CompletableFuture` 处理结果及异常情况,帮助开发者更好地理解和运用这一关键特性。
116 1
|
29天前
|
缓存 Java 数据库连接
Spring Boot奇迹时刻:@PostConstruct注解如何成为应用初始化的关键先生?
【8月更文挑战第29天】作为一名Java开发工程师,我一直对Spring Boot的便捷性和灵活性着迷。本文将深入探讨@PostConstruct注解在Spring Boot中的应用场景,展示其在资源加载、数据初始化及第三方库初始化等方面的作用。
49 0
|
1月前
|
缓存 NoSQL Java
【Azure Redis 缓存】示例使用 redisson-spring-boot-starter 连接/使用 Azure Redis 服务
【Azure Redis 缓存】示例使用 redisson-spring-boot-starter 连接/使用 Azure Redis 服务
|
3天前
|
Java 测试技术 数据库
Spring事务传播机制(最全示例)
在使用Spring框架进行开发时,`service`层的方法通常带有事务。本文详细探讨了Spring事务在多个方法间的传播机制,主要包括7种传播类型:`REQUIRED`、`SUPPORTS`、`MANDATORY`、`REQUIRES_NEW`、`NOT_SUPPORTED`、`NEVER` 和 `NESTED`。通过示例代码和数据库插入测试,逐一展示了每种类型的运作方式。例如,`REQUIRED`表示如果当前存在事务则加入该事务,否则创建新事务;`SUPPORTS`表示如果当前存在事务则加入,否则以非事务方式执行;`MANDATORY`表示必须在现有事务中运行,否则抛出异常;
24 4
Spring事务传播机制(最全示例)
|
1天前
|
Java Spring 容器
Spring使用异步注解@Async正确姿势
Spring使用异步注解@Async正确姿势,异步任务,spring boot
|
1天前
|
XML 前端开发 Java
控制spring框架注解介绍
控制spring框架注解介绍
|
14天前
|
Java 数据库连接 数据格式
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
IOC/DI配置管理DruidDataSource和properties、核心容器的创建、获取bean的方式、spring注解开发、注解开发管理第三方bean、Spring整合Mybatis和Junit
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
|
29天前
|
监控 安全 Java
【开发者必备】Spring Boot中自定义注解与处理器的神奇魔力:一键解锁代码新高度!
【8月更文挑战第29天】本文介绍如何在Spring Boot中利用自定义注解与处理器增强应用功能。通过定义如`@CustomProcessor`注解并结合`BeanPostProcessor`实现特定逻辑处理,如业务逻辑封装、配置管理及元数据分析等,从而提升代码整洁度与可维护性。文章详细展示了从注解定义、处理器编写到实际应用的具体步骤,并提供了实战案例,帮助开发者更好地理解和运用这一强大特性,以实现代码的高效组织与优化。
48 0
|
Java Maven 数据库
【Spring】Spring常用配置-Profile
【Spring】Spring常用配置-Profile
309 0
【Spring】Spring常用配置-Profile