java - 如何自动装配在其他类中使用 @service 注释的 bean
问题描述
在SPRING BOOT application
我有一个类如下
@Service
public class XYZ{
}
我想在其他类 ABC 中使用上面
public class ABC{
@Autowired
private XYZ xyx;
}
它会抛出无法找到 XYZ 的错误。我已经在编写 main 方法的类中有@SpringBootApplication。因此,这将自动在包上启用@ComponentScan。我的理解是,由于 XYZ 已使用@service 进行注释,因此 spring 扫描并创建和注册该 bean。如何在不使用 xml 配置的情况下访问其他类中的 bean?
解决方案
那么你的 ABC 类也需要有 @Service 或 @Component 注释。否则,您将收到带有以下消息的警告。
自动装配的成员必须在有效的 Spring bean (@Component|@Service|...) 中定义。
@Service
public class ABC {
@Autowired
private XYZ xyx;
}
推荐阅读
- sql - Oracle Query 使用条件获取特定日期
- javascript - 带有反射问题的片段着色器three.js
- c# - 为什么在 asp .net core 2.1 的每次迁移中都会删除种子角色?
- android - 从 onActivityResult 返回后,带有 BottomSheetBehavior 的视图显示在屏幕中央
- java - 运行应用程序时无法将字符串转换为 JSONObject 错误
- rpa - Uipath RPA 自动化屏幕抓取错误
- vue.js - Additionally pushed items are undefined when trying to access via index in v-for loop
- android - Native crash in /system/lib64/libart.so
- jquery - 使用 JQuery 很好地将 HTML 元素添加到 DOM
- node.js - NodeJS website uploaded to Heroku won't load, can't find dependencies for some reason