Based on the XML configuration Spring automatic assembly

A Learn mode automatic assembly Spring

Traditional XML Bean arranged below the key code components

<bean id="userMapper" class="edu.cn.dao.UserMapperImpl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

<bean id="userService" class="edu.cn.dao.UserServiceImpl">
    <property name="userMapper" ref="userMapper"/>
</bean>

We attribute Bean injected into the desired value by <property> tag, when Bean components require maintenance and the need to inject more attributes, is bound to increase the workload configuration. Then you can use the automatic assembly.

Second, the automatic assembly for each specified component embodiment Bean

Autowiring modify the configuration code is as follows

<bean id="userMapper" class="edu.cn.dao.UserMapperImpl" autowire="byName"/>

<bean id="userService" class="edu.cn.dao.UserServiceImpl" autowire="byName"/>

autowire Properties <bean> element specifies the automatic assembly by providing, instead of dependencies specified by Bean <property> tag display. BeanFactory inspection by the content of XML configuration files, Bean is automatically injected dependencies.

Spring assembly provides several automatic mode, autowire attribute values ​​used are as follows

  • no not use automated assembly. Bean dependency property elements must be defined
  • Automatic assembly according byType attribute type. Find all BeanFactory Bean container, if there is a just and rely on the same property type Bean, automatically assembling this property; if more than one such Bean, Spring Bean can not decide which is injected, it throws a fatal exception; if not matching Bean, then nothing will happen, the property will not be set
  • byName automatic assembly according to the attribute name. Find all BeanFactory Bean container, and to find setter method id attribute to the Senate that match Bean. Find automatically injected, or do nothing
  • Similar to the constructor byType manner, except that it applies to constructor arguments. If consistent with the constructor parameter type Bean is not found in the container, it will throw an exception

It can be automatically assembled by autowire Properties <bean> Spring element in the configuration file. However, if you want to configure a lot of Bean, Bean is configured autowire each property will be very complicated, is it possible without a unified set automatically configure each Bean inject it?

Third, set global automatic assembly

 

Guess you like

Origin www.cnblogs.com/yanguobin/p/11703372.html