2

I have the below class which should be initialized only if active profile is not master. But it is being executed even if the active profile is master. How to implement this? I am using Spring boot and Spring 4.

@Component
@Scope(value= "singleton")
@Profile("!master")
public final class SystemStartUp implements ApplicationListener<ContextRefreshedEvent>, Ordered {
}
Debopam
  • 3,198
  • 6
  • 41
  • 72
  • are you starting any other profiles with it master? – Darren Forsythe Feb 22 '18 at 19:51
  • No. master in the only profile – Debopam Feb 22 '18 at 19:52
  • "... If a given profile is prefixed with the NOT operator (!), the annotated element will be registered if the profile is not active." (see https://docs.spring.io/spring/docs/4.3.14.RELEASE/spring-framework-reference/htmlsingle/#beans-definition-profiles-java) So, there must be some other configuration pulling that component into your application context regardless of the profile. Can you provide more code? – Georg Wittberger Feb 22 '18 at 20:08

2 Answers2

5

There's no support for @Profile for ApplicationListener or @EventListener for that matter. @Profile is mostly used in combination with @Configuration.

When Spring sees a class which implements the ApplicationListener interface, it automatically registers the listener.

If you want to do some conditionally based action on start up of your system, you might want to explore different approaches.

hovanessyan
  • 30,580
  • 6
  • 55
  • 83
2

I achieved the solution programmatically.

public void onApplicationEvent(ContextRefreshedEvent event) {
        Environment env = ApplicationContextProvider.getApplicationContext().getBean(Environment.class);

        if(env.getActiveProfiles() != null) {
            if(env.getActiveProfiles().length == 1 && Arrays.binarySearch(env.getActiveProfiles(), "master") == -1 ) {
                initialize();
            }
        }

    }
Debopam
  • 3,198
  • 6
  • 41
  • 72