gpt4 book ai didi

java - 基于 Spring java 的配置,在导入的配置中具有作用域原型(prototype)

转载 作者:行者123 更新时间:2023-11-29 05:14:42 26 4
gpt4 key购买 nike

是否可以使用原型(prototype)范围创建基于导入的 java 配置的 bean?

我的意思是如果我有下面的示例代码:

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(
SpringTopLevelConfig.class);

for (int i = 0; i < 2; i++) {
System.out.println(applicationContext.getBean(Student.class));
}

在哪里

public class Notebook {
static int idCounter = 1;
private final int id;

@Override
public String toString() {
return "Notebook{" +
"id=" + id +
'}';
}

public Notebook() {
id = idCounter++;
}
}

public class Student {
private final Notebook notebook;

@Override
public String toString() {
return "Student{" +
"notebook=" + notebook +
'}';
}

public Student(Notebook notebook) {
this.notebook = notebook;
}
}

Spring Config 是:

@Configuration
public class SpringTopLevelConfig {

@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Bean
Notebook notebook(){
return new Notebook();
}

@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Bean
Student student(){
return new Student(notebook());
}
}

正如预期的那样,每个学生都有自己的笔记本:

Student{notebook=Notebook{id=1}}
Student{notebook=Notebook{id=2}}

但是,如果我尝试跨多个类拆分配置,我发现的所有示例都建议使用 @Autowire 来完成此操作:

@Configuration
@Import(SpringConfigSecondLevel.class)
public class SpringTopLevelConfig {

@Autowired
Notebook notebook;

@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Bean
Student student(){
return new Student(notebook);
}
}

@Configuration
public class SpringConfigSecondLevel {

@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Bean
Notebook notebook(){
return new Notebook();
}
}

但是现在学生们最终共享一个笔记本,这不是我想要实现的行为。

Student{notebook=Notebook{id=1}}
Student{notebook=Notebook{id=1}}

是否有一种 spring 方法可以通过拆分配置类来实现 SCOPE_PROTOTYPE 行为,或者我是否需要创建一个 NotebookFactory bean 来避免学生在同一个笔记本上互相争斗?

最佳答案

两个配置文件方法没有预期的结果,因为您在 SpringTopLevelConfig 类中 Autowiring 笔记本。该笔记本实例将被创建一次,并从所有其他学生对象中使用,因为当您创建学生时,在学生构造函数中您传递该笔记本实例而不是 notebook() bean 方法。您可以通过 Autowiring 整个配置类在学生构造函数中传递 notebook() bean 方法,以便您可以调用它:

@Configuration
@Import(SpringConfigSecondLevel.class)
public class SpringTopLevelConfig {


@Autowired SpringConfigSecondLevel springConfigSecondLevel;

@Scope("prototype")
@Bean
Student student(){
return new Student(springConfigSecondLevel.notebook());
}
}

@Configuration
public class SpringConfigSecondLevel {

@Scope("prototype")
@Bean
Notebook notebook(){
return new Notebook();
}
}

关于java - 基于 Spring java 的配置,在导入的配置中具有作用域原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27006870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com