(Turn) @Autowired (required = false) injection of attention problems

1 Introduction

In the spring using the development process, we basically use @Autowired this annotation is used to inject an existing bean. But sometimes, it will inject fail. When we add parameters (required = false) can be solved. Today, I am finishing a practical example in the development of

2, required attributes

  • @Autowired (required = true): When using @Autowired notes, in fact, the default is @Autowired (required = true), was filled when the bean must exist, otherwise it will fail injection.

  • @Autowired (required = false): Indicates to ignore the current to be injected bean, if there is a direct injection, without skipping, does not complain.

3, using

We will use normal injection service in the Controller layer, injected mapper in service in.

But if there is a common method, you need to inject an element, and this method in the common module. When the module is introduced into the other items, the item to be injected and the bean desired, a similar error [2] will appear as shown in FIG. So the question is, we do not need the project to be injected class, making the entire project error.

4, analyze and address the causes

During startup of the container will initialize many bean, which is one of spring's core (IOC). But during the injection, the scan to a common method to inject the bean, did not find, forcibly injected into the injection will fail. We alone can not change the method of removal, so we take the idea is to have bean to inject, no not injected. The solution is @Autowired (required = false).

5, the relationship between father and son vessel

As shown by the log:

We can see through the log, the startup sequence container.

  • First load the parent container (spring), after loading the sub-container (springmvc). Therefore, the Controller is injected inside the service, the parent bean container has been initialized, the normal injection.
  • Parent-child container, the container is visible parent container element pairs, the elements of the sub-tank parent container does not visible. So the parent container element of the child container can not be obtained, but the child can get the container element of the parent container.
  • 当前容器均可获取当前容器中的元素,也就是说在service中可以注入其他service。

但是,当前容器不可以注入自己。这样就会不停的注入自己,陷入死循环。从而找不到要注入的bean。如图:

 

Guess you like

Origin www.cnblogs.com/cat520/p/11703313.html