Spring @ComponentScan教程

来源:这里教程网 时间:2026-02-17 21:31:09 作者:

Spring @ComponentScan 教程显示了如何在 Spring 应用中启用组件扫描。 通过组件扫描,可以通过 Spring 容器自动检测咖啡豆。

Spring 是用于创建企业应用的流行 Java 应用框架。

Spring @ComponentScan

@ComponentScan注释启用 Spring 中的组件扫描。 Spring 会自动检测以@Component,@Configuration和@Service等构造型修饰的 Java 类。 使用@ComponentScan's basePackages属性指定应扫描哪些包装中的装饰豆。

@ComponentScan注释是<context:component-scan> XML 标签的替代方法。

Spring @ComponentScan示例

该应用允许使用@ComponentScan进行组件扫描。 我们有一个返回当前时间的服务 bean。

pom.xmlsrc├───main│   ├───java│   │   └───com│   │       └───zetcode│   │           │   Application.java│   │           └───service│   │                   TimeService.java│   └───resources│           logback.xml└───test    └───java

这是项目结构。

pom.xml

<?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>11</maven.compiler.source>        <maven.compiler.target>11</maven.compiler.target>        <spring-version>5.1.3.RELEASE</spring-version>    </properties>    <dependencies>        <dependency>            <groupId>ch.qos.logback</groupId>            <artifactId>logback-classic</artifactId>            <version>1.2.3</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>1.6.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 应用。

resources/logback.xml

<?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 日志库的配置文件。

com/zetcode/service/TimeService.java

package com.zetcode.service;import org.springframework.stereotype.Service;import java.time.LocalTime;@Servicepublic class TimeService {    public LocalTime getTime() {        var now = LocalTime.now();        return now;    }}

TimeService类带有@Service注解。 Spring 在组件扫描的帮助下将其注册为托管 Bean。

com/zetcode/Application.java

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")@Configurationpublic 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:java10:57:01.912 INFO  com.zetcode.Application - The time is 10:57:01.912235800

我们运行该应用。

在本教程中,我们使用@ComponentScan启用了组件扫描。

相关推荐