问题
Let’s assume I have two Spring boot projects. The first project is just a supporting library providing various functionalities. The second is the “main” project (primary library) which uses the supporting project (jar).
The supporting library has some services which should be autowired by the primary project.
How can I configure the supporting library so that the primary library does not have to do any configurations for the supporting library. In essence I am talking about component scan.
What I have read so far is, that the primary library has to include the packages of the supporting library in component scan. Is this really true? I hope not, because in my opinion a supporting library should do all its configurations by its own and another library (or project) just using this supporting library should not have to deal with the configuration of the supporting library.
In essence I am wondering if it is possible that a supporting library configures itself via a @Configuration
annotation or that like (or @SpringBootApplication
) so that another library does not have to deal with all that details of the other library. I really hope that this does work somehow because I think it is kind of extremely wired that another library has to do the job for it’s supporting library in regard of their configuration.
回答1:
Okay, I just found the solution by my own.
The trick is as follows.
In the supporting project there is a configuration class (that one I had already, but it was not taken into account). The configuration class of the supporting library basically looks as follows:
@SpringBootApplication
public class SupportLibApplication {
}
The primary project also has a configuration class. The trick is to include in the configuration class of the primary project the configuration class of the supporting class. This was my missing link. The configuration class of the primary project now looks that like:
@SpringBootApplication
@Import({SupportLibApplication.class})
public class QuestApplication extends WebMvcConfigurerAdapter {
…
}
回答2:
You need to add a dependency spring-boot-configuration-processor
in your project, like @M. Deinum mentioned. Here's the link of a working example. However, I haven't found a way to have multiple beans when using this method.
Another way to do this is shown in this answer on Stack Overflow.
来源:https://stackoverflow.com/questions/38776005/how-to-avoid-to-configure-an-external-library-by-another-library-using-spring-bo