Spring ApplicationContext加载后,有什么方法可以扫描所有@Component,例如带注释的类

时间:2019-03-08 21:32:05

标签: java spring spring-boot

我想在ApplicationContext加载后将@Component类添加到spring容器中。但是我不能使用BeanFactory。因为我正在使用BeanFactory,所以必须为这些类定义bean。但是我无法定义它(如果我不使用反射)。因为这些类将在运行时由ClassLoader加载。

例如

@Component
public class Service {

    private final CustomerService customerService;
    private final OrderService orderService;
    private final PaymentService paymentService;

    @Autowired
    public Service(CustomerService customerService, OrderService orderService, PaymentService paymentService) {
        this.customerService = customerService;
        this.orderService = orderService;
        this.paymentService = paymentService;
    }
}

在此示例中,Spring在应用程序调用时为此类创建bean。无需使用@Bean定义bean。但是我想要的是编译spring项目并从另一个项目中加载这些clases并添加到Spring ApplicationContext中。所以我可以自动接线。否则,我必须在运行时使用反射创建bean。如果我使用反射,则将递归调用所有依赖类。

是否可以在不使用运行时使用反射的情况下创建bean的任何方式。

2 个答案:

答案 0 :(得分:1)

如果我理解正确:您有一些标有@Component的类,并且您希望Spring管理其生命周期?

此帮助:https://springframework.guru/spring-component-scan/吗? @ComponentScan专门或在XML配置中类似:

 <context:component-scan base-package="org.example"/>

答案 1 :(得分:1)

我找到了解决方法。

    ConfigurableApplicationContext context = SpringApplication.run(EventServiceApplication.class, args);
    // Load class ...
    context.start();

如果我们在加载类之后运行context.start()方法,则像类bean一样创建spring @Component并放入spring容器。