Spring @ComponentScan 教程
最后修改于 2023 年 10 月 18 日
Spring @ComponentScan 教程展示了如何在 Spring 应用程序中启用组件扫描。组件扫描使 Spring 容器能够自动检测 bean。
Spring 是一个流行的 Java 应用程序框架,用于创建企业级应用程序。
Spring @ComponentScan
@ComponentScan 注解在 Spring 中启用组件扫描。用诸如 @Component、@Configuration、@Service 等立体声注解的 Java 类可以被 Spring 自动检测到。@ComponentScan 的 basePackages 属性指定了应该扫描哪些包以查找被注解的 bean。
@ComponentScan 注解是 <context:component-scan> XML 标签的替代方案。
Spring @ComponentScan 示例
该应用程序使用 @ComponentScan 启用组件扫描。我们有一个服务 bean,它返回当前时间。
pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ │ Application.java
│ │ └───service
│ │ TimeService.java
│ └───resources
│ logback.xml
└───test
└───java
这是项目结构。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zetcode</groupId>
<artifactId>componentscan</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<spring-version>5.3.23</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<mainClass>com.zetcode.Application</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
在 pom.xml 文件中,我们有基本的 Spring 依赖 spring-core、spring-context 和日志 logback-classic 依赖。
exec-maven-plugin 用于从 Maven 命令行执行 Spring 应用程序。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<logger name="org.springframework" level="ERROR"/>
<logger name="com.zetcode" level="INFO"/>
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
</Pattern>
</encoder>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="consoleAppender" />
</root>
</configuration>
logback.xml 是 Logback 日志库的配置文件。
package com.zetcode.service;
import org.springframework.stereotype.Service;
import java.time.LocalTime;
@Service
public class TimeService {
public LocalTime getTime() {
var now = LocalTime.now();
return now;
}
}
TimeService 类用 @Service 注解进行注解。在组件扫描的帮助下,它被 Spring 注册为一个托管 bean。
package com.zetcode;
import com.zetcode.service.TimeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@ComponentScan(basePackages = "com.zetcode")
@Configuration
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
var ctx = new AnnotationConfigApplicationContext(Application.class);
var timeService = (TimeService) ctx.getBean("timeService");
logger.info("The time is {}", timeService.getTime());
ctx.close();
}
}
该应用程序用 @ComponentScan 进行注解。basePackages 选项告诉 Spring 在 com/zetcode 包及其子包中查找组件。
var ctx = new AnnotationConfigApplicationContext(Application.class);
AnnotationConfigApplicationContext 是一个 Spring 独立的应用程序上下文。它接受被注解的 Application 作为输入;因此,扫描被启用。
var timeService = (TimeService) ctx.getBean("timeService");
logger.info("The time is {}", timeService.getTime());
我们获取已注册的服务 bean 并调用其方法。
$ mvn -q exec:java 10:57:01.912 INFO com.zetcode.Application - The time is 10:57:01.912235800
我们运行应用程序。
在本文中,我们使用 @ComponentScan 启用了组件扫描。
作者
列出 所有 Spring 教程。