spring parent-child container

Special Instructions:

ContextLoaderListener: The created container is the parent container (applicationContext.xml)

DispatcherServlet: The created container is a sub-container (appServlet-context.xml)

1. Question: Can instances of the same class be generated by both the child container and the parent container at the same time?

Answer: Yes, and a different instance

2. Question: If a class sub-container (appServlet-context.xml) has an instance, and the parent container (applicationContext.xml) also has an instance, which one does getBean use?

Answer:

1. Take from the parent container: is an instance of the parent container,

2. Get the value from the sub-container: use the instance of the sub-container first; the sub-container does not try to get the value from the parent container

3. Question: Does the child container (DispatcherServlet) support AOP?

Answer: support

Notice:

1. Make sure that the configuration file of the corresponding container (appServlet-context.xml/applicationContext.xml) has AOP-related configuration such as <aop:aspectj-autoproxy/>

2. The AOP implantation logic of the sub-container configuration is invalid for the parent container; that is, the configuration is only valid for the instance of the current container;

Essentially, when an instance is created, because the current container has an AnnotationAwareAspectJAutoProxyCreator instance that implements the BeanPostProcessor interface, when a bean object is created, an AOP proxy is generated to have the AOP function.

4. Question: Does the subcontainer support transactions?

Answer: Yes, same as AOP, appServlet-context.xml file must have corresponding configuration

Notice:

1. Only configure <tx:annotation-driven/> in appServlet-context.xml, instances loaded by non-sub-containers have no transaction capability

2. Configure <tx:annotation-driven/> in both parent and child containers: they are independent transactions and have nothing to do with each other. Essentially the same as the principle of AOP


Summarize:

1. It is unnecessary to use the parent-child container to avoid having a common instance.

     Common resource initialization and preheating multiple times;

     如果父子容器都有实例,而通过SpringUtil 的方式获取bean,就要看SpringUtil 所在的容器,来获取对应的bean,也容易混乱

2、事务一般不要放在子容器中,子容器应该仅仅存在 web相关的bean;这也间接说明@Transactional 不应该修饰controller

3、如果希望对子容器的实例拥有事务能力,需要确保<aop:aspectj-autoproxy/> 以及Aspect 配置在子容器中

 

http://wangxinchun.iteye.com/blog/2341197

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326616460&siteId=291194637