首页 > 解决方案 > 如何自动装配在其他类中使用 @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?

标签: javaspringspring-bootspring-bean

解决方案


那么你的 ABC 类也需要有 @Service 或 @Component 注释。否则,您将收到带有以下消息的警告。

自动装配的成员必须在有效的 Spring bean (@Component|@Service|...) 中定义。

@Service
public class ABC {

    @Autowired
    private XYZ xyx;
}

推荐阅读