view raw
Adam Boczek Adam Boczek - 11 months ago 260
Java Question

Spring @PostConstruct depending on @Profile

I'd like to have multiple @PostConstruct annotated methods in one configuration class, that should be called dependent on the @Profile. You can imagine a code snipped like this:

public class SilentaConfiguration {

private static final Logger LOG = LoggerFactory.getLogger(SilentaConfiguration.class);

private Environment env;

@PostConstruct @Profile("test")
public void logImportantInfomationForTest() {"********** logImportantInfomationForTest");

@PostConstruct @Profile("development")
public void logImportantInfomationForDevelopment() {"********** logImportantInfomationForDevelopment");

However according to the javadoc of @PostConstruct I can only have one method annotated with this annotation. There is an open improvement for that in Spring's Jira

How do you solved this requirement? I can always split this configuration class into multiple classes, but maybe you have a better idea/solution.

BTW. The code above runs without problems, however both methods are called regardless of the profile settings.


You can check for profile with Environment within a single @PostContruct.

An if statement would do the trick.

Regards, Daniel