Spring单例模式线程安全问题

spring中默认bean是单例模式,对于大部分无状态的情况下是没问题的,但是如果有成员变量会出现线程安全问题,解决方案是设置scope为 prototype,同时proxyMode设置成target_class或者interfaces。但是会遇到另外的问题,看下下面代码:


@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TestScope {

    String name;

    public void call() {
        this.name = "123";
    }

    public void call2() {
        System.out.println(this.name);
    }
}

如果在外面分别调用call(),call2()的话会输出什么?以及为什么?

阅读 2.7k
2 个回答

看你怎么调了

新手上路,请多包涵

调用场景:

public class TestController{
    
    @Autowired
    TestScope testScope


    public void test(){
        testScope.call();
        testScope.call2();
    }
}

这里其实输入的还是null。 原因是因为testScope是使用动态代理方式调用,两次的testScope其实是生成了两个不同的对象,这样第一个testScope设置的变量值在第二个testScope对象里是拿不到的,所以输入null

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题