I will inject with @ Autowired
in Spring Boot, but I will write about what to do if there is a case where you want to change the target to be read for each environment.
The environment here is the Spring Boog startup argument spring.profiles.active
, and when this startup argument is changed, the class to be read is changed.
Java10 Spring Boot2.0.4.RELEASE
Since it was made a while ago, the environment is old, but it should work with Java 11 and Boot 2.1 series.
First, prepare an interface (an abstract class is also possible).
public interface TestInterface {
void print();
}
Since we want to change the target to be read for each environment, we will generate two classes that implement the interface above.
Modify these two classes with startup arguments.
Suppose you give test and
test2` as arguments.
@Service
@Profile("test")
public class TestServiceA implements TestInterface {
public void print() {
System.out.println("test");
}
}
@Service
@Profile("test2")
public class TestServiceB implements TestInterface {
public void move() {
System.out.println("test2");
}
}
Just add @Profile
.
If this is added, if the startup arguments do not match, it will not be converted to Bean.
This time we will use this class from Controller.
@Controller
public class TestController {
@Autowired
private TestInterface testInterface;
//Controller processing
}
Just set the target class to interface. Since there is only one target that is a Bean in Profile, the target changes depending on the startup argument.
Recommended Posts