简体   繁体   中英

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.
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 ?

The @Component -scanning behaviour of <context:component-scan> is only the default. You can customize its behaviour using name-based filters. See section 3.10.3 of the manual for an example:

<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.

The 3rd option is using the @Configuration and @Bean Annotations and using the Java-based container configuration . But then you are writing code to wire your dependencies together and create your beans.

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.

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.

Yes, this requires coding though and is not something that you get out of the box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM