@Profile
can't be used for that, but you might as well code your own @RunOnProfile
annotation and aspect. Your method would look like this:
@RunOnProfile({"dev", "uat"})
public void doSomething() {
log.info("I'm doing something on dev and uat");
}
Or
@RunOnProfile("!prod")
public void doSomething() {
log.info("I'm doing something on profile other than prod");
}
Here's the code for the @RunOnProfile
annotation and aspect:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RunOnProfile {
String[] value();
@Aspect
@Configuration
class RunOnProfileAspect {
@Autowired
Environment env;
@Around("@annotation(runOnProfile)")
public Object around(ProceedingJoinPoint joinPoint, RunOnProfile runOnProfile) throws Throwable {
if (env.acceptsProfiles(runOnProfile.value()))
return joinPoint.proceed();
return null;
}
}
}
Note 1: If you expect something in return and the profile does not apply, you would get null
.
Note 2: This work like any other Spring aspect. You need to invoke the autowired bean method, for the bean proxy to kick in. In other words, you can't invoke the method directly from other class method. If you want that, you need to self autowire the component, on the class and invoke self.doSomething()
.