prototype 注入 singleton 后会每次创建吗?
不会自动每次创建。单例的依赖通常在该单例创建时解析一次,之后访问同一单例里的那个字段仍是同一个对象。需要按调用获取新实例时,可以使用 ObjectProvider 等延迟获取方式,并单独测试调用路径。
singleton 是每个容器、每个 bean 定义一个共享实例,不是整个 JVM 只能有一个实例。prototype 是每次向容器请求该 bean 时创建,不能据此保证线程安全。
复现实验
先采用依赖版本与完整 Maven 配置中的 POM。将下面完整测试类保存为 src/test/java/site/ScopeExampleTest.java,在项目目录执行 mvn -Dtest=ScopeExampleTest test。首次运行需要下载依赖。
package site;
import java.util.*;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.*;
import org.springframework.core.*;
import static org.junit.jupiter.api.Assertions.*;
class ScopeExampleTest {
static class Sample {}
record Holder(Sample sample) {}
@Configuration static class Scopes {
@Bean @Scope("prototype") Sample sample() { return new Sample(); }
@Bean Holder holder(Sample sample) { return new Holder(sample); }
}
@Test void scopes() {
try (var context = new AnnotationConfigApplicationContext(Scopes.class)) {
assertSame(context.getBean(Holder.class), context.getBean(Holder.class));
assertNotSame(context.getBean(Sample.class), context.getBean(Sample.class));
assertSame(context.getBean(Holder.class).sample(), context.getBean(Holder.class).sample());
System.out.println("singleton=true; prototype=true; injected-prototype-reused=true");
}
}
}
预期输出 singleton=true; prototype=true; injected-prototype-reused=true,三个断言分别验证共享 Holder、两次直接获取 Sample 不同、Holder 内 Sample 被复用。
使用边界
本实验是普通 ApplicationContext,未测试 request、session 等 Web 作用域。prototype 对象的完整销毁清理由使用方负责,不能假定关闭容器会调用所有原型实例的销毁方法。有可变状态的 singleton 也需要自行处理并发。
下一步:Bean 初始化与销毁顺序。
整理范围与出处
本次依据下方版本资料整理说明与示例;历史导入资料的来源状态单独列示,不将技术参考认作原作者信息。原始发布日期与地址保留。