문제

Spring creates the class objects by Java dynamic proxies (java.lang.reflect.Proxy). i.e

@Component
public class NewsService implements Service{
}

But how the member variables are injected by Spring? ie

@Autowired
private EntityManager em;

Java dynamic proxies uses interface (i.e Service) to create the objects. But how member variables are injected? The instance variables are not known by interface.

Also when member instances are injected? Load time?(When containing class object is created?) or Lazy loading? (when object is used first?)

도움이 되었습니까?

해결책

Few facts for you:

  • Spring instantiates specific classes, not interfaces. Dependency injection is done on the original bean instance.
  • When a proxy is created, Spring registers both the original bean and its proxy in the application context. JDK proxy is created for all interfaces implemented by the original bean.
  • Proxies are not created if they are not necessary (i.e. no aspect is applied on the target bean).
  • All beans are eagerly initialized by default. If you want some bean to be instantiated in a lazy fashion, you need to specify it explicitly.
  • Dependency injection happens right after the bean is instantiated. Some dependencies are injected based on the bean definition, other dependencies might be injected by various bean post processors (but they are executed right away as well).

How is dependency injection realized:

  • When using XML configuration or autowiring , dependency injection is done via Reflection API. Spring is able to either call property setter (setFoo(...)) or set field value directly (reflection allows setting private members).
  • When using @Bean methods in Java configuration, dependency injection is done by your method.

A bit on proxies:

  • JDK proxies and CGLIB proxies are two different proxying mechanisms. JDK creates artificial class based on provided interfaces, whereas CGLIB creates artificial subclass of the target class.
  • Which proxying mechanism is used depends on your Spring configuration (JDK is the default one). For obvious reasons JDK proxy can be used only in cases when your dependencies are referenced only by interface. From the other side you can not use CGLIB proxying for final classes.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top