Автор оригинала: mkyong.
В этом примере мы покажем вам, как установить активный @Профиль
в веб-приложении Spring MVC.
@Configuration public class AppConfig { @Profile("dev") @Bean public CacheManager cacheManager() { //... } @Profile("live") @Bean public EhCacheManagerFactoryBean ehCacheCacheManager() { //... } @Profile("testdb") @Bean public DataSource dataSource() { //... } }
Чтобы установить активный @Профиль
весной определите значение через spring.profiles.active
системное свойство.
1. @Профиль || весной определите значение через || spring.profiles.active || системное свойство.
Для обычного веб-приложения, которое содержит web.xml
файл.
1.1 Установите активный профиль.
spring.profiles.active live
1.2 Установите несколько активных профилей.
spring.profiles.active dev, testdb
2. Сервлет 3.0+ Контейнер
Для веб-приложения нет web.xml
файл, используйте один из следующих методов:
2.1 Переопределение На старте
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
.
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; }*/ }
Рекомендации
Оригинал: “https://mkyong.com/spring-mvc/spring-mvc-how-to-set-active-profile/”