Spring @Профиль позволяет разработчикам регистрировать компоненты по условию. Например, зарегистрируйте компоненты на основе операционной системы (Windows, *nix), в которой работает ваше приложение, или загрузите файл свойств базы данных на основе приложения, запущенного в среде разработки, тестирования, промежуточной или производственной среды.
В этом уроке мы покажем вам приложение Spring @Profile , которое выполняет следующие действия:
- Создайте два профиля –
devиlive - Если профиль “dev” включен, верните простой менеджер кэша –
Менеджер параллельных карт - Если включен профиль “live”, верните расширенный менеджер кэша –
EhCacheCacheManager
- Spring поддерживает аннотации @Profile начиная с версии 3.1
- @Профиль находится внутри spring-context.jar
Используемые инструменты:
- Пружина 4.1.4. ВЫПУСК
- Ehcache 2.9.0 Ehcache 2.9.0
- JDK 1.7
1. Примеры профилей Spring @
Эта @Profile аннотация может быть применена на уровне класса или метода.
1.1 Обычная конфигурация Spring, включите кэширование, чтобы Spring ожидал менеджера кэша во время выполнения.
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 A dev профиль, который возвращает простой менеджер кэша Менеджер параллельных карт
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 A живой профиль, который возвращает Менеджер кэша ehcache
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. Включить @Профиль
Несколько фрагментов кода, которые покажут вам, как включить профиль Spring.
2.1 Для не-веб-приложения вы можете включить профиль с помощью контекстной среды Spring.
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
Или, через системное свойство, подобное этому
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.xml
spring.profiles.active live
2.3 Для веб-приложения нет web.xml , как контейнер сервлета 3.0+
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
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 @Профиль может применяться на уровне метода.
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");
spring.profiles.active stage, postgresql
@ActiveProfiles({"dev", "mysql","integration"})
((ConfigurableEnvironment)context.getEnvironment())
.setActiveProfiles(new String[]{"dev", "embedded"});
Скачать Исходный Код
Рекомендации
- Профили Пружин – Абстракция среды
- Пример Весеннего Кэширования И Ehcache
- Spring MVC – Установить активный профиль
Оригинал: “https://mkyong.com/spring/spring-profiles-example/”