4

How can I switch between two method calls of the same name based on the environment?

I know that this can be done at the class level with @Profile, but is there a way to do this at the method level? So ideally, I would want something like the below snippet.

Example

public class Foo {

    @Profile('local')
    public void bar() {...}

    @Profile('prod')
    public void bar() {...}
  • 3
    There isn't. Just create 2 instances of a bean, put an interface in front of it and use 1 of the 2 implementations based on the `@Profile`. – M. Deinum May 11 '18 at 15:01

1 Answers1

1

Since Spring 4.x is possible newly to control the profile directly with annotating by @Profile on the method level.

... as a method-level annotation on any @Bean method

Personally, I do not use profiles on the method level, read more at Is Spring's @Profile on methods a good practice?


In your case, I rather suggest you the following approach:

Create two classes and make the implement the common interface.

public interface Foo {
    public void bar();
}

Annotate each with @Profile based on the environment.

@Component
@Profile("local")
public class LocalFoo implements Foo {

    @Override
    public void bar() { ... }
}

@Component
@Profile("prod")
public class ProdFoo implements Foo {

    @Override
    public void bar() { ... }
}

Since now, they are ready to be injected according to the active profile.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183