When I setup Spring with XML a can override component definitions in XML files that are loaded later. It's very usefull for tests - I create default config set and than load it with addition test configuration that replaces some of components with specials (stubs, mocks, and so on). Now i start to migrate to annotation based configurations and it causes some problems.
The direct way to use annotations is auto-discovering of packages with @Component
So I have
@Configuration
@ComponentScan({"some.pack1", "some.pack2"})
public class ProductConfig{}
And when @Configuration @Import({ProductConfig.class}) @ComponentScan({"test.pack"}) public class TestConfig{}
But it will cause conflict if I try to override components in test.pack
And what I can do?
After some investigations where are 3 answers with some issues on them
What is best and standard way to override conigurations??? When I used XML-based it was not a problem...
@profile plays a crucial role while implementing the testing strategy for your service/code.
For example, in development, you may have:
public interface DataSource{
public String getHost();
}
Default implementation is
@Component
@Profile("Prod")
public class DevDataSource implements DataSource {
public String getHost(){
// return actual value
}
And the implementation for component tests(Fake impl)
@Component
@Profile("test")
public class StubbyDataSource implements DataSource {
public String getHost(){
return "some-host"; // return mocked data
}
Now you can write a test here which can act as integration test, unit test and component tests (https://martinfowler.com/bliki/ComponentTest.html)
In that way, your testing strategy would be much more elegant, concise and easy to maintain. Just by changing the profile, the same test can point to different environments (real or fake).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments