How to skip a Service class if the Spring profile is different than one specified, using the annotation @Profile

StackOverflow https://stackoverflow.com/questions/22760985

문제

I have a service class marked with the annotations:

@Service(value="myService")
@Profile("test")
public class MyServiceImpl implements MyService{
 ...
 }

Therefore if the current Spring profile is "test" the methods of this class will be used for the service myService. While, I would like also to have another class with the same annotations maybe with @Profile("!test") that be be loaded in all other cases when the profile is not test,
How can I do that without configuring anything in the .xml Spring configuration files? I would like to use simply annotations.

도움이 되었습니까?

해결책

You need to define another bean like so:

@Service(value="myServiceDefault")
public class MyServiceImpl implements MyService{
 ..

}

Then change your initial code for the test profile to:

@Service(value="myService")
@Profile("test")
@Primary
public class MyServiceImpl implements MyService{
 ...
 }

What this does is register an implementation for all profiles to use and then when the test profile is active is uses the other implementation because of the @Primary annotation

If you are using Spring 4 you could come up with even more elaborate configuration strategies using the @Conditional annotation

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top