[英]How can I make Spring identify beans without using xml or annotations?
I'm trying to integrate Spring framework into an existing project that contains thousands of pojos. 我正在尝试将Spring框架集成到包含数千个pojos的现有项目中。
Writing an xml configuration file or going through each file and annotating the classes will be a tough time-consuming task, so is there a way to make Spring scan packages and identify the beans based solely on name convention ? 编写xml配置文件或遍历每个文件并为类添加注释将是一项艰巨的耗时任务,因此,有没有一种方法可以使Spring扫描程序包并仅基于名称约定来标识bean?
The @Component
-scanning behaviour of <context:component-scan>
is only the default. <context:component-scan>
的@Component
-scanning行为只是默认设置。 You can customize its behaviour using name-based filters. 您可以使用基于名称的过滤器来自定义其行为。 See section 3.10.3 of the manual for an example:
有关示例,请参见手册的3.10.3节 :
<beans>
<context:component-scan base-package="org.example">
<context:include-filter type="regex" expression=".*Stub.*Repository"/>
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>
So you can make it detect your beans by the naming convention of the classes. 因此,您可以通过类的命名约定使它检测到您的bean。
The 3rd option is using the @Configuration and @Bean Annotations and using the Java-based container configuration . 第三个选项是使用@Configuration和@Bean批注以及使用基于Java的容器配置 。 But then you are writing code to wire your dependencies together and create your beans.
但是随后您正在编写代码以将依赖项连接在一起并创建您的bean。
The first question you need to ask yourself is, is it really necessary to wire all those beans? 您需要问自己的第一个问题是,是否真的有必要对所有这些豆进行接线? Out of all the objects in your system only a small subset really need to be wired: those that are configurable and those that have dependencies on other wired beans.
在系统中的所有对象中,实际上只需要连接一小部分:那些是可配置的,并且依赖于其他连接的bean。
Agree with Bozho. 同意博佐。
There is a workaround - you can define your own custom BeanFactoryPostProcessor , where you can put the logic for scanning through the classes in your existing project based on your naming conventions and registering the BeanDefinitions for the classes in your existing project. 有一个解决方法-您可以定义自己的自定义BeanFactoryPostProcessor ,在其中可以放置逻辑以根据命名约定在现有项目中的类之间进行扫描,并为现有项目中的类注册BeanDefinitions。
Yes, this requires coding though and is not something that you get out of the box. 是的,尽管这需要编码,但并不是开箱即用的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.