Spring component auto-Scan details and instance code, spring details
Detailed description of automatic Spring component scanning and instance code
Problem description
A system usually has thousands of components. If you need to manually add all components to the spring container for management, it is a huge project.
Solution
Spring provides the component scanning function. It can automatically scan, detect, and instantiate components with specific annotations from classpath. The basic annotation is @ Component, which identifies a Component managed by Spring. Other specific annotations include @ Repository, @ Service, and @ Controller, which respectively identify the components of the persistence layer, Service layer, and presentation layer.
Implementation Method
User. Java
package com.zzj.bean; import javax.annotation.Resource; import org.springframework.stereotype.Component; @Component public class User { @Resource private Car car; public void startCar(){ car.start(); } }
Car. java
package com.zzj.bean; import org.springframework.stereotype.Component; @Component public class Car { public void start(){ System.out.println("starting car..."); } }
XML configuration file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.zzj.bean"/> </beans>
Note: after Spring's automatic scanning function is enabled, the automatic injection function is also enabled.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!