简体   繁体   中英

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. i have a Demo Bean with an @Async method that just print this.hashCode(). and a Main class that injected by Demo. The Demo bean'scope is singleton. but in fact, in Main class, the demo.hashcode() is not equal to this.hashCode() in the method test() of Demo class. 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. To support @Async Spring places the concrete object inside a proxy to wrap the @Async logic around the concrete method call. Therefore you get the hashCode value of the proxy.

When invoking demo.hashCode() you are returning the hashCode() of the concrete object and not the proxy anymore. Therefore they differ.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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