原文: http://zetcode.com/spring/单例scope/

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

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

Spring 单例 bean

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

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

Spring 单例 bean 示例

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

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>scopesingletonex</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <properties>
  11. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  12. <maven.compiler.source>11</maven.compiler.source>
  13. <maven.compiler.target>11</maven.compiler.target>
  14. <spring-version>5.1.3.RELEASE</spring-version>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>ch.qos.logback</groupId>
  19. <artifactId>logback-classic</artifactId>
  20. <version>1.2.3</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework</groupId>
  24. <artifactId>spring-context</artifactId>
  25. <version>${spring-version}</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework</groupId>
  29. <artifactId>spring-core</artifactId>
  30. <version>${spring-version}</version>
  31. </dependency>
  32. </dependencies>
  33. <build>
  34. <plugins>
  35. <plugin>
  36. <groupId>org.codehaus.mojo</groupId>
  37. <artifactId>exec-maven-plugin</artifactId>
  38. <version>1.6.0</version>
  39. <configuration>
  40. <mainClass>com.zetcode.Application</mainClass>
  41. </configuration>
  42. </plugin>
  43. </plugins>
  44. </build>
  45. </project>

pom.xml文件中,我们具有基本的 Spring 依赖项spring-corespring-context和日志记录logback-classic依赖项。

exec-maven-plugin用于在命令行上从 Maven 执行 Spring 应用。

resources/my.properties

  1. myapp.name=ScopeSingleton
  2. myapp.author=Jan Bodnar

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

resources/logback.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3. <logger name="org.springframework" level="ERROR"/>
  4. <logger name="com.zetcode" level="INFO"/>
  5. <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
  6. <encoder>
  7. <Pattern>%d{HH:mm:ss.SSS} [%thread] %blue(%-5level) %magenta(%logger{36}) - %msg %n
  8. </Pattern>
  9. </encoder>
  10. </appender>
  11. <root>
  12. <level value="INFO" />
  13. <appender-ref ref="consoleAppender" />
  14. </root>
  15. </configuration>

logback.xml是 Logback 日志库的配置文件。

com/zetcode/bean/Message.java

  1. package com.zetcode.bean;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.PropertySource;
  4. import org.springframework.context.annotation.Scope;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. @Scope("单例") // change to prototype
  8. @PropertySource("classpath:my.properties")
  9. public class Message {
  10. @Value("${myapp.name}")
  11. private String name;
  12. @Value("${myapp.author}")
  13. private String author;
  14. public String getMessage() {
  15. return String.format("Application %s was created by %s", name, author);
  16. }
  17. }

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

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

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

com/zetcode/Application.java

  1. package com.zetcode;
  2. import com.zetcode.bean.Message;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  6. import org.springframework.context.annotation.ComponentScan;
  7. @ComponentScan(basePackages = "com.zetcode")
  8. public class Application {
  9. private static final Logger logger = LoggerFactory.getLogger(Application.class);
  10. public static void main(String[] args) {
  11. var ctx = new AnnotationConfigApplicationContext(Application.class);
  12. var app = ctx.getBean(Application.class);
  13. var bean1 = ctx.getBean(Message.class);
  14. var bean2 = ctx.getBean(Message.class);
  15. app.run(bean1, bean2);
  16. ctx.close();
  17. }
  18. public void run(Message a, Message b) {
  19. logger.info("running Application");
  20. logger.info(a.getMessage());
  21. if (a.equals(b)) {
  22. logger.info("The beans are the same");
  23. } else {
  24. logger.info("The beans are not the same");
  25. }
  26. }
  27. }

这是主要的应用类。

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

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

  1. logger.info(a.getMessage());

我们从 bean 中读取消息。

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

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

  1. $ mvn -q exec:java
  2. 21:28:35.573 [com.zetcode.Application.main()] INFO com.zetcode.Application - running Application
  3. 21:28:35.575 [com.zetcode.Application.main()] INFO com.zetcode.Application - Application ScopeSingleton was created by Jan Bodnar
  4. 21:28:35.576 [com.zetcode.Application.main()] INFO com.zetcode.Application - The beans are the same

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

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

您可能也对这些相关教程感兴趣: Spring 原型作用域 beanSpring 应用的JdbcTemplateSpring 注入列表 XML 教程Spring 中BeanDefinitionBuilder教程Spring HikariCP 教程Java 教程