ZetCode

Spring 单例作用域 bean

最后修改于 2023 年 10 月 18 日

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

Spring 是一个流行的 Java 应用程序框架,用于创建企业级应用程序。

Spring 单例 bean

单例 bean 在 Spring 容器创建时被创建,在容器销毁时被销毁。单例 bean 是共享的;每个 Spring 容器只创建一个单例 bean 实例。单例作用域是 Spring bean 的默认作用域。

其他 bean 作用域包括:prototype、request、session、global session 和 application。

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>scopesingletonex</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-corespring-context,以及日志 logback-classic 依赖。

exec-maven-plugin 用于从 Maven 命令行执行 Spring 应用程序。

resources/my.properties
myapp.name=ScopeSingleton
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("singleton") // 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("singleton") // change to prototype
@PropertySource("classpath:my.properties")
public class Message {

@Scope("singleton") 注解不是必需的;如果未指定,默认作用域就是单例。使用 @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:java
21:28:35.573 [com.zetcode.Application.main()] INFO  com.zetcode.Application - running Application
21:28:35.575 [com.zetcode.Application.main()] INFO  com.zetcode.Application - Application ScopeSingleton was created by Jan Bodnar
21:28:35.576 [com.zetcode.Application.main()] INFO  com.zetcode.Application - The beans are the same

我们运行应用程序。将 Message bean 的作用域更改为 prototype 并比较结果。

在本篇文章中,我们处理了一个单例 Spring bean。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 Spring 教程