Debopam
Debopam

Reputation: 3356

Spring component initialization by Profile is not working

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 {
}

Upvotes: 2

Views: 1832

Answers (2)

Debopam
Debopam

Reputation: 3356

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();
            }
        }

    }

Upvotes: 2

hovanessyan
hovanessyan

Reputation: 31443

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.

Upvotes: 5

Related Questions