spring @Autowired 和 getBean() 的区别(多例 prototype)

最近在项目中有一个service中使用了类成员变量,导致了业务并发。(多个人同时使用一个功能)

于是就在此service上添加注解(@Scope("prototype"))使用多例,但是问题出现了,添加了此注解还是存在此问题,于是看了spring Autoware 的加载机制,网上有很多资料,看后也做了测试,得出一下结论。

使用 @Autoware 注入service (多例)  其实每个方法使用的都是同一个service对象,并未出现多例模式,测试代码

    @Autowired
    private ScopeTestService scopeTestService;
    @GetMapping("/test1")
    @ResponseBody
    public ServerResponse test1(){
        scopeTestService.test1();
        log.info(scopeTestService.toString());
        return ServerResponse.createBySuccess("test1");
    }
    @GetMapping("/test2")
    @ResponseBody
    public ServerResponse test2(){
        scopeTestService.test2();
        log.info(scopeTestService.toString());
        return ServerResponse.createBySuccess("test2");
    }

结果:此方式访问两个接口打印的scopeTestService 是一样的  com.barton.service.impl.ScopeTestServiceImpl@49c4d534

使用getBean 获取 scopeTestService 成功

    private ScopeTestService scopeTestService;
    @GetMapping("/test1")
    @ResponseBody
    public ServerResponse test1(){
        scopeTestService = SpringContextUtils.getBean(ScopeTestService.class);
        log.info(scopeTestService.toString());
        scopeTestService.test1();
        return ServerResponse.createBySuccess("test1");
    }
    @GetMapping("/test2")
    @ResponseBody
    public ServerResponse test2(){
        scopeTestService = SpringContextUtils.getBean(ScopeTestService.class);
        log.info(scopeTestService.toString());
        scopeTestService.test2();
        return ServerResponse.createBySuccess("test2");
    }

结果:此方式访问两个接口打印的scopeTestService 是不一样的

 

以上是@Autoware 和 getBean()在多例模式上的小小区别,至于其他方面的区别没再去细细研究

其实多例模式下直接将第一中方式的Controller 变为多例模式也可以解决并发问题,简单粗暴。

 

你可能感兴趣的:(java,springboot)