文章出處

前言

譯文鏈接: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

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()