我使用 Spring Bean 创建一个实例并 Autowiring 该类,并且通过设置数据中的字段从不同的类返回相同的 Autowiring 字段对象。
第一次,数据正确传入,但在第二次 REST 调用时,每次都反射(reflect)相同的对象。我尝试过使用 Scope("prototype"),但它只是第一次有帮助。如何获取每个请求的正确数据?
@Service
@Scope(value="singleton",proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MessageStats {
private int count;
//Setter & Getter
}
@Component
public class Main1 {
@Autowired
MessageStats messageStats;
public MessageStats getStats() {
// At runtime the data is populated for example: the first time as 10 and second time as 11
messageStats.setCount(10);
}
}
@Component
public class Main2 {
@Autowired
MessageStats messageStats;
public MessageStats getStats() {
// At runtime the data is populated for example: first time as 12 and second time as 13
messageStats.setCount(12);
}
}
输出:
First time
10
12
Second time
10 expected is 11
12 expected is 13
这里的问题是在我的第二个 API 请求中,messageStats 值被保留,我需要在每次请求时将该值刷新为零,然后我将重新填充数据。
最佳答案
而不是 @Scope("prototype")
使用@Scope("singleton")
https://www.baeldung.com/spring-bean-scopes
关于java - Spring Autowired 实例在每个请求上始终相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58991506/