Как установить активные профили в конфигурации Java на основе аннотаций Spring

установить активный профиль, такой как context.getEnvironment().setActiveProfiles( "DEV" );, который может быть достигнут с помощью

public class SpringWebInitializer implements WebApplicationInitializer
{

    public void onStartup( final ServletContext servletContext ) throws ServletException
    {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.getEnvironment().setActiveProfiles("DEV" )

    }
}

Но при расширении AbstractAnnotationConfigDispatcherServletInitializer . как мы можем добиться установки активного профиля?

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

}

person arun kumar    schedule 12.07.2016    source источник


Ответы (4)


Активируйте свой профиль, используя свойство spring.profiles.active.

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

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

}
person dieter    schedule 12.07.2016

У вас есть несколько вариантов..

  1. Вы можете попробовать использовать инициализатор контекста для загрузки профиля пружины из файла свойств в пути к классам, например:

    public class ContextProfileInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(ContextProfileInitializer.class);
    
        private static final String DEFAULT_SPRING_PROFILE = "local";
    
        @Override
        public void initialize(final ConfigurableApplicationContext applicationContext) {
    
            ConfigurableEnvironment environment = applicationContext.getEnvironment();
            try {
                    environment.getPropertySources().addFirst(new ResourcePropertySource("classpath:conf/application.properties"));
                    if (environment.getProperty("spring.profiles.active") == null) {
                        environment.setActiveProfiles(DEFAULT_SPRING_PROFILE);
                    }
                    LOGGER.info("Activated Spring Profile: " + environment.getProperty("spring.profiles.active"));
                } catch (IOException e) {
                    LOGGER.error("Could not find properties file in classpath.");
                }
       }
    
    }
    

Вот несколько руководств с дополнительной информацией:

https://gist.github.com/rponte/3989915

http://www.java-allandsundry.com/2014/09/spring-webapplicationinitializer-and.html

  1. В качестве альтернативы (и гораздо более простого!) Используйте Spring Boot.

    Вы можете просто определить spring.profiles.active в файле application.properties в пути к классам. Это будет автоматически подобрано и загружено в вашу среду.

Подробнее здесь:

http://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html

person Pete    schedule 12.07.2016

Вы можете использовать @ActiveProfiles("DEV") в некоторых из ваших @Configuration классов, но, вероятно, более полезным будет передача профиля извне - просто запустите свой .jar с дополнительным параметром, например -Dspring.active.profiles=DEV

person freakman    schedule 12.07.2016
comment
спасибо за ответ @ActiveProfiles(DEV) находится в тестовых примерах. Есть ли другой лучший способ настройки Java. - person arun kumar; 12.07.2016

Я думаю, что это должно быть скорее: -Dspring.profiles.active=... (Spring 4.1.5)

person Zenek73    schedule 12.10.2018