spring-conditional、width = 320、height = 221

Spring `@ Profile`は開発者が条件でBeanを登録できるようにします。たとえば、アプリケーションが実行されているオペレーティングシステム(Windows、** nix)に基づいてBeanを登録するか、開発、テスト、ステージング、または運用環境で動作するアプリケーションに基づいてデータベースプロパティファイルをロードします。

このチュートリアルでは、Springの `@ Profile`アプリケーションを紹介します。このアプリケーションでは、次のことが行われます。


  1. dev`と

    live`の2つのプロファイルを作成します

  2. プロファイル “dev”が有効になっている場合は、単純なキャッシュマネージャを返します.


ConcurrentMapCacheManager

。プロファイル「ライブ」が有効になっている場合は、高度なキャッシュマネージャーを返します。


EhCacheCacheManager

使用されるツール:

  1. Spring 4.1.4.RELEASE

  2. Ehcache 2.9.0

  3. JDK 1.7

1. Spring @Profileの例

この `@ Profile`アノテーションは、クラスレベルまたはメソッドレベルで適用できます。

1.1通常のSpring Configuration:キャッシングを有効にします。これにより、Springは実行時にキャッシュマネージャを期待します。

AppConfig

package com.mkyong.test;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
@ComponentScan({ "com.mkyong.** " })
public class AppConfig {
}

1.2単純なキャッシュマネージャ

concurrentMapCacheManager`を返す

dev`プロファイル

CacheConfigDev.java

package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile("dev")
public class CacheConfigDev {

    private static final Logger log = LoggerFactory.getLogger(CacheConfigDev.class);

    @Bean
        public CacheManager concurrentMapCacheManager() {
        log.debug("Cache manager is concurrentMapCacheManager");
                return new ConcurrentMapCacheManager("movieFindCache");
        }

}

1.3

ehCacheCacheManager`を返す

live`プロファイル

CacheConfigLive.java

package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource;

@Configuration
@Profile("live")
public class CacheConfigLive {

    private static final Logger log = LoggerFactory.getLogger(CacheConfigDev.class);

    @Bean
    public CacheManager cacheManager() {
        log.debug("Cache manager is ehCacheCacheManager");
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
        cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cmfb.setShared(true);
        return cmfb;
    }

}

2. @Profileを有効にする

Springプロファイルを有効にする方法を示すコードスニペットはほとんどありません。

2.1非Webアプリケーションの場合、Springコンテキスト環境を介してプロファイルを有効にすることができます。

App.java

package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {

    public static void main(String[]args) {

      AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
     //Enable a "live" profile
      context.getEnvironment().setActiveProfiles("live");
      context.register(AppConfig.class);
      context.refresh();

      ((ConfigurableApplicationContext) context).close();

    }
}

出力

DEBUG com.mkyong.test.CacheConfigDev - Cache manager is ehCacheCacheManager

または、このようなシステムプロパティを介して

App.java

package com.mkyong.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.AbstractEnvironment;

public class App {

    public static void main(String[]args) {

     //Enable a "dev" profile
      System.setProperty(AbstractEnvironment.ACTIVE__PROFILES__PROPERTY__NAME, "dev");
      ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

    }
}

出力

DEBUG com.mkyong.test.CacheConfigDev - Cache manager is concurrentMapCacheManager

2.2 Webアプリケーションの場合、 `web.xml`にコンテキストパラメータを定義しました。

web.xml

    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>live</param-value>
    </context-param>

2.3 Webアプリケーションの場合、サーブレット3.0コンテナのように `web.xml`はありません

MyWebInitializer.java

package com.mkyong.servlet3;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

public class MyWebInitializer extends
    AbstractAnnotationConfigDispatcherServletInitializer {

   //...
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.setInitParameter("spring.profiles.active", "live");
    }

}

2.4単体テストでは、 `@ ActiveProfiles`を使います。

CacheManagerTest.java

package com.mkyong.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.cache.CacheManager;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class })
@ActiveProfiles("dev")
public class CacheManagerTest {

    @Autowired
    private CacheManager cacheManager;

    @Test
    public void test__abc() {
       //...
    }

}

3.もっと…​

3.1 Springの `@ Profile`はメソッドレベルで適用できます。

AppConfig.java

package com.mkyong.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.ClassPathResource;

@Configuration
@EnableCaching
@ComponentScan({ "com.mkyong.** " })
public class AppConfig {

    private static final Logger log = LoggerFactory.getLogger(AppConfig.class);

    @Bean
    @Profile("dev")
        public CacheManager concurrentMapCacheManager() {
        log.debug("Cache manager is concurrentMapCacheManager");
                return new ConcurrentMapCacheManager("movieFindCache");
        }

    @Bean
    @Profile("live")
    public CacheManager cacheManager() {
        log.debug("Cache manager is ehCacheCacheManager");
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());
    }

    @Bean
    @Profile("live")
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
        cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cmfb.setShared(true);
        return cmfb;
    }

}

3.2複数のプロファイルを有効にすることができます。

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.getEnvironment().setActiveProfiles("live", "linux");
   //or
    System.setProperty(AbstractEnvironment.ACTIVE__PROFILES__PROPERTY__NAME, "dev, windows");

web.xml

    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>stage, postgresql</param-value>
    </context-param>

    @ActiveProfiles({"dev", "mysql","integration"})

        ((ConfigurableEnvironment)context.getEnvironment())
                   .setActiveProfiles(new String[]{"dev", "embedded"});

ソースコードをダウンロードする

ダウンロードする – リンク://wp-content/uploads/2015/01/Spring-Profiles-Example.zip[Spring-Profiles-Example.zip](17 KB)

参考文献

プロファイル – 環境抽象化]。リンク://spring/spring-caching-and-ehcache-example/[Spring Caching And

Ehcacheの例]。リンク://spring-mvc/spring-mvc-how-set-active-profile/[Spring MVC –

アクティブなプロファイルを設定]