Search code examples
javaspringspring-profiles

Spring Profiles on method level?


I'd like to introduce some methods that are only executed during development.

I thought I might use Spring @Profile annotation here? But how can I apply this annotation on class level, so that this method is only invoked if the specific profile is configured in properties?

spring.profiles.active=dev

Take the following as pseudocode. How can this be done?

class MyService {

    void run() { 
       log();
    }

    @Profile("dev")
    void log() {
       //only during dev
    }
}

Solution

  • AS you can read on http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/Profile.html

    The @Profile annotation may be used in any of the following ways:

    as a type-level annotation on any class directly or indirectly annotated with @Component, including @Configuration classes as a meta-annotation, for the purpose of composing custom stereotype annotations If a @Configuration class is marked with @Profile, all of the @Bean methods and @Import annotations associated with that class will be bypassed unless one or more the specified profiles are active. This is very similar to the behavior in Spring XML: if the profile attribute of the beans element is supplied e.g., , the beans element will not be parsed unless profiles 'p1' and/or 'p2' have been activated. Likewise, if a @Component or @Configuration class is marked with @Profile({"p1", "p2"}), that class will not be registered/processed unless profiles 'p1' and/or 'p2' have been activated.

    So, a @Profile annotation on a class, aplies to all of it's methods and imports. Not to the class.

    What you're trying to do could probably be achieved by having two classes that implement the same interface, and injecting one or another depending on the profile. Take a look at the answer to this question.

    Annotation-driven dependency injection which handles different environments