Spring component automatic scanning detailed explanation and example code
Problem description
A system often has thousands of components, and it is a huge project to manually incorporate all components into spring containers.
Solution
Spring provides component scanning function. It can automatically scan, detect and instantiate components with specific annotations from the classpath. The basic annotation is @Component, which identifies a component managed by Spring. Other specific annotations are @Repository, @Service, and @Controller, which identifies the components of the persistence layer, service and presentation layer, respectively.
Implementation method
package ; import ; import ; @Component public class User { @Resource private Car car; public void startCar(){ (); } }
package ; import ; @Component public class Car { public void start(){ ("starting car..."); } }
XML configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="/schema/beans" xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:context="/schema/context" xsi:schemaLocation="/schema/beans /schema/beans/ /schema/context /schema/context/"> <context:component-scan base-package=""/> </beans>
Note: When Spring's automatic scanning function is enabled, the automatic injection function is also enabled.
Thank you for reading, I hope it can help you. Thank you for your support for this site!