如何在 Spring 引导应用程序中自动装配其他 class 中的 bean?

How to autowire a bean in other class in a Spring Boot application?

在 Spring 启动应用程序中,我有一个 class 如下:

@Service
public class XYZ{
}

我想在其他 class ABC 中使用上面的内容,例如:

public class ABC{

    @Autowired
    private XYZ xyx;

}

它抛出找不到 XYZ 的错误。我已经在编写主要方法的 class 中有 @SpringBootApplication。因此,这将自动在包上启用@ComponentScan。 ABC 在 spring 配置文件中创建为 bean。我的理解是,由于 XYZ 已使用 @service 进行注释,因此 spring 扫描并创建并注册该 bean。如何在不使用 xml 配置的情况下访问其他 class 中的那个 bean?

ABC是如何实例化的? ABC 对象必须由 Spring.

实例化

换句话说,ABC class 也必须是某种 @Component。它可以由 @SpringBootApplication 自动装配,或者在 Web 应用程序的情况下,它可以是 @Controller.

除了上面 @Sharon Ben Asher 所说的之外:以防万一在测试执行期间抛出错误并且如果测试上下文使用 @SpringBootTest 以外的任何内容,那么还有一个该上下文不扫描 @Service 注释 bean 的机会。

例如,用 @DataJpaTest 注释的测试 class 不会扫描 @Service 个 bean;它需要一个明确的 @ComponentScan 来解析它。有关示例片段的详细信息,请参见此处 .