Spring Prototype 作用域 bean 教程展示了如何在 Spring 应用中使用 Prototype 作用域 bean。
Spring 是用于创建企业应用的流行 Java 应用框架。
Spring 原型 bean
原型 bean 每次针对该 bean 发出新请求时都会创建。
其他 bean 范围是:单例,请求,会话,全局会话和应用。
Spring 原型 bean 示例
该应用将创建两个原型范围内的 bean,并检查它们是否相同。 该应用是经典的 Spring 5 控制台应用。
────src├───main│ ├───java│ │ └───com│ │ └───zetcode│ │ │ Application.java│ │ ││ │ └───bean│ │ Message.java│ ││ └───resources│ logback.xml│ my-beans.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.0http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.zetcode</groupId><artifactId>prototypescopedbean</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-beans.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="com.zetcode"/></beans>
通过context:component-scan标签,我们指示 Spring 在com.zetcode包中查找 bean。 它将找到我们唯一的Message bean,并用@Component装饰。
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.context.annotation.Scope;import org.springframework.stereotype.Component;@Component@Scope("prototype")public class Message {private String message;public String getMessage() {return message;}}
Message是由 Spring 容器管理的 Spring bean。 它具有原型范围。
@Component@Scope("prototype")public class Message {
@Scope("prototype")将 bean 的范围设置为原型。 默认值为单例。
com/zetcode/Application.java
package com.zetcode;import com.zetcode.bean.Message;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.support.GenericXmlApplicationContext;public class Application {private static final Logger logger = LoggerFactory.getLogger(Application.class);public static void main(String[] args) {var ctx = new GenericXmlApplicationContext("my-beans.xml");var beanA = ctx.getBean(Message.class);var beanB = ctx.getBean(Message.class);if (beanA.equals(beanB)) {logger.info("The beans are identical");} else {logger.info("The beans are not identical");}ctx.close();}}
这是主要的应用类。
var ctx = new GenericXmlApplicationContext("my-beans.xml");
我们使用GenericXmlApplicationContext从my-beans.xml文件创建 Spring 应用上下文。
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");}
我们测试两个豆是否相同。
$ mvn -q exec:java21:26:03.089 [com.zetcode.Application.main()] INFO com.zetcode.Application - The beans are not identical
我们运行该应用。 将Message bean 的范围更改为单例并比较结果。
在本教程中,我们使用了原型 Spring bean。
您可能也对这些相关教程感兴趣:经典的 Spring 应用中的 JdbcTemplate , Spring 单例范围 bean , Spring ClassPathResource教程, Spring 注入列表 XML 教程, Spring BeanDefinitionBuilder教程, Spring HikariCP 教程和 Java 教程。
