Spring bean 没有从自定义库中自动连接
我由自己的库(com.custom.mylib)创建,它返回如下所示的字符串。
@Component
public class MyLibrary{
@Value("${str.message}")
private String message; //This val should come from app which is going to use this lib
public String readMessage() {
return message;
}
我已经创建了一个将使用上述库的项目。我已将 lib 作为 pom 依赖项包含在内。但是当我尝试从我的应用程序调用库方法时。我收到以下错误。 如何解决呢?
@Autowired
private MyLibrary myLibrary;
考虑在您的 配置。
我还在 application.properties 文件中添加了以下内容,以便库可以获取该值
str.message=Hello world
I have created by own library(com.custom.mylib) which returns a string like below.
@Component
public class MyLibrary{
@Value("${str.message}")
private String message; //This val should come from app which is going to use this lib
public String readMessage() {
return message;
}
I have create a project which is going to use above library. I have included the lib as pom dependency .But when I try to call library method from my app. I get the error below.
How to resolve it?
@Autowired
private MyLibrary myLibrary;
Consider defining a bean of type 'com.custom.mylog.MyLibrary' in your
configuration.
I also have below in application.properties file so that library can pick the value up
str.message=Hello world
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我似乎得到了解决方案。我需要创建 META-INF 文件并执行 org.springframework.boot.autoconfigure.EnableAutoConfiguration=
如此处给出的
Spring Boot:从库项目自动装配 bean
I got the solution it seems.I need to create META-INF file and do
org.springframework.boot.autoconfigure.EnableAutoConfiguration=<fully_qualified_name_of_configuration_file>
as given here
Spring Boot: autowire beans from library project
由于它必须用作外部库,因此您可以通过
@Configuration
文件实例化它:我使用的规则如下(这不是通用规则):
@Autowired
。这是注入依赖项的推荐方法。@Configuration
注释实现 Java 配置,以将外部类实例化为 bean。@Component
装饰它。@Qualifier
并在@Configuration
类中定义您的 bean。As it has to be used as a external library, you can instantiate it throught a
@Configuration
file:The rule I used is the follow (this is not an universal rule):
@Autowired
in your constructor. It is the recommanded way to inject your dependencies.@Configuration
annotation, to instanciate your external classes as beans.@Component
.@Qualifier
and define your beans in a@Configuration
class.