0

我需要在应用程序启动之前执行代码。

我写了以下监听器(在 web.xml 中注册):

Profile("test")
public class H2Starter extends ContextLoaderListener {


    @Override
    public void contextInitialized(ServletContextEvent event) {    
        System.out.println("invoked")
    }    

}

我希望只有在test配置文件被激活时才会调用监听器。
但它总是调用。如何解决这种行为?

4

2 回答 2

0

据我了解,弹簧型材仅适用于配置

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

似乎配置文件注释不适用于您提到的场景。

于 2015-12-24T05:48:20.393 回答
0

根据文档@Profile注释只能应用于@Component@Configuration。无论如何,您无法在 ContextLoaderListener 中获取有关配置文件的信息,因为尚未加载 ApplicationContext。如果您想在应用程序启动时调用您的代码,我的建议是创建ApplicationListener并收听ContextRefreshEvent

@Component
public class CustomContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Environment environment = contextRefreshedEvent.getApplicationContext().getEnvironment();
        if(environment.acceptsProfiles("test")){
            System.out.print("Test profile is active");
        }
    }
}

第一次将在应用程序初始化后调用此侦听器。如果您要在上下文初始化之前获取配置文件信息,您可以创建新的上下文加载器:

public class ProfileContextListener extends ContextLoaderListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        if(isProfileActive("test", event.getServletContext())){
            System.out.println("Profile is active");
        }
    }

    private boolean isProfileActive(String profileName, ServletContext context) {
        String paramName = "spring.profiles.active";            
        //looking in web.xml
        String paramValue = context.getInitParameter(paramName);
        if(paramValue==null) {
            //if not found looking in -D param
            paramValue = System.getProperty(paramName);
        };
        if(paramValue==null) return false;
        String[] activeProfileArray = paramValue.split(",");
        for(String activeProfileName : activeProfileArray){
            if(activeProfileName.trim().equals(profileName)) return true;
        }
        return false;
    }
}

要激活所需的配置文件,您必须添加到 web.xml 特殊的 spring 环境属性 - spring.profiles.active

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>default,test</param-value>
</context-param>

或者您可以设置配置文件 throw -D jvm-option

-Dspring.profiles.active=default,test

请注意,您可以添加多个用逗号分隔的配置文件名称。

于 2015-12-24T01:56:55.517 回答