是否可以将包中的所有类注册为Spring bean? [英] Is it possible to register all classes within a package as Spring beans

查看:394
本文介绍了是否可以将包中的所有类注册为Spring bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉基于Spring Java的配置选项,包括使用 @Component @Configuration in结合使用 @Bean 注解来注册Spring beans。

然而,当将体面大小的项目转换为Spring时,可以非常费力地系统地触摸项目中的所有类并使用 @Configuration @Bean s进行更新,或者对每个类进行注释类与 @Component 。我们有一个大的Groovy项目需要转换,我想简化这个过程。



我的问题:Spring中是否提供了一个工具它允许你告诉Spring在特定的包中自动配置所有有效的bean候选类?



如果不是,还有哪些其他选项可用? code> ClassPathBeanDefinitionScanner 就是您所需要的。

  public class Main {
public static void main(String [] args){
GenericApplicationContext context = new GenericApplicationContext();
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context,false);
scanner.addIncludeFilter((metadataReader,metadataReaderFactory) - > true);
scanner.scan(net.company.name);
context.refresh();

A a = context.getBean(A.class);
System.out.println(a.toString());




$ b你可以在包含过滤器中传递自定义逻辑如果你想要。在当前版本中,提供的包中的每个类都将作为一个bean包含在内。



但是,在类中自动构建正确的依赖关系是不可能的,你想要的范围。你需要用手去做。


I'm familiar with Springs Java based configuration options, including the usage of @Component and @Configuration in conjunction with @Bean annotations to register Spring beans.

However, when converting a decent size project to Spring, it can be very labor intensive to systematically touch all classes in the project and update with @Configuration @Beans or annotating each class with @Component. We have a large Groovy project to be converted and I would like to simplify the process.

My question: Is there a facility provided in Spring that allows you to tell Spring to auto-configure all valid bean candidate classes within a specific package?

If not, what other options are available?

解决方案

ClassPathBeanDefinitionScanner is all you need.

public class Main {
    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, false);
        scanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> true);
        scanner.scan("net.company.name");
        context.refresh();

        A a = context.getBean(A.class);
        System.out.println(a.toString());
    }
}

You can pass custom logic in include filter if you want. In current version every class in the provided package will be included as a bean.

But it is impossible to build a right dependency structure on your classes automagically, it really depends on the scope you want. You need to do it by your hands.

这篇关于是否可以将包中的所有类注册为Spring bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆