是否可以将包中的所有类注册为Spring bean? [英] Is it possible to register all classes within a package as Spring beans
问题描述
我熟悉基于Spring Java的配置选项,包括使用 @Component
和 @Configuration
in结合使用 @Bean
注解来注册Spring beans。
@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
@Bean
s 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屋!