Spring Autowired 实例在每次请求时始终相同

Spring Autowired instance is always same on every request

我正在使用 Spring Bean 创建一个实例并自动装配 class 并且相同的自动装配字段对象通过在数据中设置字段从不同的 classes 返回。

第一次,数据正常,但在第二次 REST 调用时,每次都反映同一个对象。我曾尝试使用 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

如果一个单例bean(即Main1Main2)有一个原型bean作为它的依赖,原型bean只在创建单例bean时被创建并注入到单例bean中一次。稍后单例bean 访问原型bean 时,它不会创建另一个新的原型bean。此行为在 the documentation.

中得到了很好的解释

如果想在单例bean访问原型bean的时候创建一个新的原型实例,有很多options.

例如,我会使用:

public class Main1{

     @Autowired
     Provider<MessageStats> messageStats;

     public MessageStats getStats(){
        messageStats.get().setCount(10);
     }
 }

Prototype 在每次请求时都会创建一个新对象,因此它不会保存状态。