Spring Profiles on method level?

membersound picture membersound · Mar 12, 2014 · Viewed 53.8k times · Source

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

Answer

Niels Masdorp picture Niels Masdorp · Oct 19, 2015

For future readers who don't want to have multiple @Beans annotated with @Profile, this could also be a solution:

class MyService {

   @Autowired
   Environment env;

   void run() { 
      if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
         log();
      }
   }

   void log() {
      //only during dev
   }
}