Java tutorial configure bean component assembly through annotation

Component assembly

  1. demand

Controller components often need to use instances of Service components, and Service components often need to use instances of Repository components. Spring can help us realize the assembly of attributes through annotations. Java training course

  • Realization basis

When specifying the package to be scanned, the <context:component-scan> element will automatically register a bean post processor: an instance of AutowiredAnnotationBeanPostProcessor. The post processor can automatically assemble the attributes annotated with @Autowired , @Resource, or @Inject. Java training course

  • @Autowired annotation

① Realize automatic assembly according to type.

② Constructors, ordinary fields (even non-public), and all methods with parameters can be applied @Autowired annotation Java training tutorial

③By default, all attributes annotated with @Autowired need to be set. When Spring cannot find a matching bean assembly attribute, it will throw an exception.

④ If an attribute is allowed not to be set, you can set the required attribute of the @Autowired annotation to false

⑤By default, when there are multiple types of compatible beans in the IOC container, Spring will try to match whether the id value of the bean is the same as the variable name, and if they are the same, the assembly will be performed. If the id value of the bean is not the same, auto-wiring via type will not work. At this time, you can provide the bean name in the @Qualifier annotation. Spring even allows @Qualifiter annotations on the formal parameters of methods to specify the name of the injected bean. Java training course

⑥@Autowired annotation can also be applied to the attributes of the array type, at this time Spring will automatically assemble all matching beans.

⑦@Autowired annotation can also be applied to collection properties, at this time Spring reads the type information of the collection, and then automatically assembles all compatible beans.

⑧ When the @Autowired annotation is used on java.util.Map, if the key value of the Map is String, Spring will automatically assemble a bean compatible with the value type as the value, and use the id value of the bean as the key. Java training course

  • @Resource

The @Resource annotation requires a bean name attribute. If the attribute is empty, the variable or method name at the annotation will be automatically used as the bean name.

  • @Inject

The @Inject and @Autowired annotations also inject matching beans by type, but there is no reqired attribute.

Java training

Guess you like

Origin blog.csdn.net/msjhw_com/article/details/109237155