Spring 单例 作用域 bean

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

Spring 单例 作用域 bean 教程展示了如何在 Spring 应用中使用 单例 作用域 bean。

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

Spring 单例 bean

单例 bean 是在创建 Spring 容器时创建的,在销毁容器时会被销毁。 单例 bean 是共享的; 每个 Spring 容器仅创建一个 单例 bean 实例。 单例 范围是 Spring bean 的默认范围。

其他 bean 范围是:原型,请求,会话,全局会话和应用。

Spring 单例 bean 示例

该应用创建两个单例作用域 Bean,并检查它们是否相同。 该应用是经典的 Spring 5 控制台应用。

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>scope单例ex</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/my.properties

myapp.name=Scope单例myapp.author=Jan Bodnar

my.properties文件中有两个基本属性。 它们正在Message bean 中使用。

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} [%thread] %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/bean/Message.java

package com.zetcode.bean;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.PropertySource;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Component;@Component@Scope("单例") // change to prototype@PropertySource("classpath:my.properties")public class Message {    @Value("{myapp.name}")    private String name;    @Value("{myapp.author}")    private String author;    public String getMessage() {        return String.format("Application %s was created by %s", name, author);    }}

Message是由 Spring 容器管理的 Spring bean。 它具有单例范围。

@Component@Scope("单例") // change to prototype@PropertySource("classpath:my.properties")public class Message {

不需要@Scope("单例")注解; 如果未指定,默认范围是单例。 使用@PropertySource注解,我们指定属性文件。 稍后使用@Value读取属性。

com/zetcode/Application.java

package com.zetcode;import com.zetcode.bean.Message;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.ComponentScan;@ComponentScan(basePackages = "com.zetcode")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 app = ctx.getBean(Application.class);        var bean1 = ctx.getBean(Message.class);        var bean2 = ctx.getBean(Message.class);        app.run(bean1, bean2);        ctx.close();    }    public void run(Message a, Message b) {        logger.info("running Application");        logger.info(a.getMessage());        if (a.equals(b)) {            logger.info("The beans are the same");        } else {            logger.info("The beans are not the same");        }    }}

这是主要的应用类。

var bean1 = ctx.getBean(Message.class);var bean2 = ctx.getBean(Message.class);app.run(bean1, bean2);

我们从应用上下文中获取这两个 bean,并将它们传递给run()方法进行比较。

logger.info(a.getMessage());

我们从 bean 中读取消息。

if (a.equals(b)) {    logger.info("The beans are the same");} else {    logger.info("The beans are not the same");}

我们测试两个 bean 是否相同。

$ mvn -q exec:java21:28:35.573 [com.zetcode.Application.main()] INFO  com.zetcode.Application - running Application21:28:35.575 [com.zetcode.Application.main()] INFO  com.zetcode.Application - Application Scope单例 was created by Jan Bodnar21:28:35.576 [com.zetcode.Application.main()] INFO  com.zetcode.Application - The beans are the same

我们运行该应用。 将Message bean 的范围更改为原型并比较结果。

在本教程中,我们使用了 单例 Spring bean。

相关推荐