使用应用程序进行组件扫描



我制作了一个包含组件类和配置类的java库。

当我在其他spring引导服务中使用库时,bean没有注册,因为组件和配置类不在类路径中。

我知道我们可以使用@ComponentScan,但我不想改变服务的代码。是否有使用application.properties将类添加到类路径的方法?或者我可以在库中做些什么来注册这些bean吗?

如果您正在使用Spring Boot,您可以利用Spring自动配置。

为此,您需要在库的.jar文件的META-INF/spring.factories中放置一个文件spring.factories。如果您使用Gradle或Maven作为构建工具和标准文件夹结构,则文件路径为src/main/resources/META-INF/spring.factories

下面是我写的一个库中的例子:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
org.requirementsascode.spring.behavior.web.BehaviorConfiguration,
org.requirementsascode.spring.behavior.web.SerializationConfiguration,
org.requirementsascode.spring.behavior.web.BehaviorController

可以看到,在第一行(特定于Spring的行)之后,您列出了所有的配置类。

您可以在这里了解更多关于自动配置的信息,例如:

您可以使用AutowireCapableBeanFactoryautowireBean()方法来完成此操作。阅读更多:AutowireCapableBeanFactory

最新更新