简体   繁体   English

Spring bean 使用@Async 方法,为什么singleton bean 的内部hashcode 与外部不同

[英]Spring bean with @Async method, why singleton bean‘s inner hashcode is different from outside

I'm very confused with the the different behaviors in spring bean with async mehtod.我对使用异步方法的 spring bean 中的不同行为感到非常困惑。 i have a Demo Bean with an @Async method that just print this.hashCode().我有一个带有 @Async 方法的 Demo Bean,它只打印 this.hashCode()。 and a Main class that injected by Demo.和一个由Demo注入的主class。 The Demo bean'scope is singleton. Demo bean 的范围是 singleton。 but in fact, in Main class, the demo.hashcode() is not equal to this.hashCode() in the method test() of Demo class.但实际上,在Main class中,Demo class的方法test()中的demo.hashcode()不等于this.hashCode()。 why?为什么? they are not the same instance?他们不是同一个实例?

@Component
public class Demo {
    @Async
    public void test(){
        System.out.println(this.hashCode());
    } 
}
@Component
public class Main implements CommandLineRunner {

    @Autowired
    Demo demo;

    @Override
    public void run(String... args) throws Exception {
         System.out.println(demo.hashcode());
         demo.test();
    }
}

In Main you are calling the hashCode() method on the proxy object.Main中,您在代理object 上调用hashCode()方法。 To support @Async Spring places the concrete object inside a proxy to wrap the @Async logic around the concrete method call.为了支持@Async Spring 将具体的 object 放置在代理中,以将@Async逻辑包装在具体的方法调用周围。 Therefore you get the hashCode value of the proxy.因此,您将获得代理的hashCode值。

When invoking demo.hashCode() you are returning the hashCode() of the concrete object and not the proxy anymore.调用demo.hashCode()时,您将返回具体object 的hashCode()不再是代理。 Therefore they differ.因此它们不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM