春MVC – アクティブなプロファイルを設定する方法
この例では、Spring MVC Webアプリケーションでアクティブな `@ Profile`を設定する方法を説明します。
@Profileの例
@Configuration
public class AppConfig {
@Profile("dev")
@Bean
public CacheManager cacheManager() {
//...
}
@Profile("live")
@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
//...
}
@Profile("testdb")
@Bean
public DataSource dataSource() {
//...
}
}
Springでアクティブな
@ Profile`を設定するには、
spring.profiles.active`システムプロパティで値を定義します。
1. web.xml
`web.xml`ファイルを含む通常のWebアプリケーションの場合。
1.1アクティブなプロファイルを設定します。
web.xml
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>live</param-value>
</context-param>
1.2複数のアクティブなプロファイルを設定します。
web.xml
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev, testdb</param-value>
</context-param>
2.サーブレット3.0コンテナ
Webアプリケーションには `web.xml`ファイルがありません。次のいずれかの方法を使用してください:
2.1 `onStartup`を上書きする
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");
//Set multiple active profile
//servletContext.setInitParameter("spring.profiles.active", "dev, testdb");
}
}
2.2
@ Profile
beanをロードするコンテキスト(ルートまたはサーブレット)に依存します。
MyWebInitializer.java
package com.mkyong.servlet3;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
//If the @Profile beans are loaded via root context
@Override
protected WebApplicationContext createRootApplicationContext() {
WebApplicationContext context =
(WebApplicationContext)super.createRootApplicationContext();
((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles("live");
//Set multiple active profiles
//((ConfigurableEnvironment)context.getEnvironment())
// .setActiveProfiles(new String[]{"live", "testdb"});
return context;
}
//If the @Profile beans are loaded via servlet context
/**
@Override
protected WebApplicationContext createServletApplicationContext() {
WebApplicationContext context =
(WebApplicationContext)super.createServletApplicationContext();
((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles("dev");
return context;
}** /
}