java - Spring Autowired 实例在每个请求上始终相同

标签 java spring spring-boot autowired

我使用 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/

相关文章:

java - 如何使用 object.Clone 冲突方法实现接口(interface)

java - 发送列表到jsp标签

java - 如何正确关闭 Tomcat 上的 JAX-WS Spring 应用程序?

java - Spring Security 使用什么来生成 OAuth2 token ?

java - Spring Boot 2.0 - 禁用连接到数据库

java - 找不到依赖项 'com.amazonaws'

java - 流口水议程组锁定 Activity 似乎对我不起作用

java - 有没有办法将双 `for` 循环更改为 java 8 lambda 表达式?

java - 使用包裹发送未知数据类型的对象时出现问题

spring - elasticsearch 5.6.3兼容的spring数据elasticsearch版本