Spring @PostConstruct depending on @Profile
Asked Answered
U

2

10

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:

@Configuration
public class SilentaConfiguration {

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

    @Autowired
    private Environment env;

    @PostConstruct @Profile("test")
    public void logImportantInfomationForTest() {
        LOG.info("********** logImportantInfomationForTest");
    }

    @PostConstruct @Profile("development")
    public void logImportantInfomationForDevelopment() {
        LOG.info("********** 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 https://jira.spring.io/browse/SPR-12433.

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.

Uriiah answered 25/3, 2016 at 12:49 Comment(3)
Just do it yourself. The Environment can tell you if a profile is active or not. So create a simple if statement.Napiform
or split your class into two, each one with the proper @Profile annotated at class levelOfficial
Vote for this issue mate: jira.spring.io/browse/SPR-12433Brennan
U
17

I solved it with one class per @PostConstruct method. (This is Kotlin but it translates to Java almost 1:1.)

@SpringBootApplication
open class Backend {

    @Configuration
    @Profile("integration-test")
    open class IntegrationTestPostConstruct {

        @PostConstruct
        fun postConstruct() {
            // do stuff in integration tests
        }

    }

    @Configuration
    @Profile("test")
    open class TestPostConstruct {

        @PostConstruct
        fun postConstruct() {
            // do stuff in normal tests
        }

    }

}
Unexpected answered 15/6, 2016 at 15:31 Comment(1)
Works well, interestingly when I add an \@Profile(...) to my normal \@Configuration \@PostConstruct method it is ignored. Yet subclassing works and allows you to hit multiple PostConstruct if you really wanted (STS 4/Springboot 3.1.1 - not sure if it's supposed to according to spec, jakarta.ee/specifications/platform/10/apidocs/jakarta/…).Enclasp
C
9

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

An if statement would do the trick.

Regards, Daniel

Charlyncharm answered 25/3, 2016 at 13:59 Comment(1)
Can you add an example?Stubbed

© 2022 - 2024 — McMap. All rights reserved.