SpringBoot系列(二十四)依赖注入单例和多例模式

SpringBoot的依赖注入默认是单例模式,如果定义了成员变量,有可能会出现安全问题。我们先来一个单例

创建一个Service

package com.fcors.fcors.service;

import org.springframework.stereotype.Service;

@Service
public class TestService2 {

    public long invoiceCount = 0;
    public static long staInvoiceCount = 0;
    public String testScope2(int num3) {
        return "Greetings from Spring Boot! staInvoiceCount = " + String.valueOf(++staInvoiceCount)
                + " , invoiceCount= " + String.valueOf(++invoiceCount);
    }
}

创建一个TestController

@RestController
@RequestMapping("/test")
@Validated
public class TestController {
    @Autowired
    private TestService2 testService2;
    @GetMapping("/java/{num}")
    public String testxing(
            @PathVariable(name="num") Integer num3
    ){
        return testService2.testScope2(num3).toString();
    }
}

此时我们运行postman请求:

第一次请求: Greetings from Spring Boot! staInvoiceCount = 1 , invoiceCount = 1

第二次请求: Greetings from Spring Boot! staInvoiceCount = 2 , invoiceCount = 2

第三次请求: Greetings from Spring Boot! staInvoiceCount = 3 , invoiceCount = 3

结论:单例情况静态变量和非静态变量被共用

修改Service

package com.fcors.fcors.service;

import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;

@Service
@Scope(value = "prototype",proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TestService2 {

    public long invoiceCount = 0;
    public static long staInvoiceCount = 0;
    public String testScope2(int num3) {
        return "Greetings from Spring Boot! staInvoiceCount = " + String.valueOf(++staInvoiceCount)
                + " , invoiceCount= " + String.valueOf(++invoiceCount);
    }
}

此时我们运行postman请求:

第一次请求: Greetings from Spring Boot! staInvoiceCount = 1 , invoiceCount = 1

第二次请求: Greetings from Spring Boot! staInvoiceCount = 2 , invoiceCount = 1

第三次请求: Greetings from Spring Boot! staInvoiceCount = 3 , invoiceCount = 1

如果要处理静态变量,则可以考虑使用多线程处理。