Detailed Explanation and Example Code of Automatic Scanning of Spring Component

  • 2021-12-12 05:17:54
  • OfStack

Detailed Explanation and Example Code of Automatic Scanning of Spring Component

Problem description

A system often has thousands of components. If you need to manually manage all components in spring container, it is a huge project.

Solutions

Spring provides component scanning (component scanning). 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 are @ Repository, @ Service, and @ Controller, which identify components of the persistence layer, services layer, and presentation layer, respectively.

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: When the automatic scan function of Spring is turned on, the automatic injection function is also turned on.

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: