Why proxy is not used to autowire

后端 未结 2 1623
情书的邮戳
情书的邮戳 2021-01-15 03:58

I can not find any reason why every autowired bean are not autowired by proxy. I know that becasue @Transactional annotations do not work and I checked autowire

相关标签:
2条回答
  • 2021-01-15 04:20

    Proxying and auto wiring are independent of each other. When you use @AutoWired it finds another bean that implements the required interface and injects it. The bean instance it finds might be a normal object or a proxy - it doesn't matter to Autowired.

    Proxies are created for certain beans automatically by spring. As you have noticed one scenario in which this happens is when you use @Transactional. When the spring container instantiates a bean which has the @Transactional annotation the object gets wrapped in a proxy. The actual object is replaced by the proxy in the context. This is done so that spring can intercept calls to those methods and add the begin / commit transaction calls before and after the method call. This is implemented by the spring-aop module. Any feature that relies on AOP (@Transactional, @Secured) will result in creation of a proxy.

    The other case where proxies are used is to create an implementation on the fly. In case of the CRUDRepository you are required to only implement the interface. The implementation of that is created on the fly using the same proxy infrastructure.

    0 讨论(0)
  • 2021-01-15 04:29

    My guess is that you are scanning for the same components twice. You probably have a in your root context (for the ContextLoaderListener) and one for the DispatcherServlet. NO if the both scan for the same classes you end up with duplicated (and one proxied and one non proxied instance).

    0 讨论(0)
提交回复
热议问题