首页 > 代码库 > Spring 自动装配

Spring 自动装配

一、自动装配方式

1.byName(属性),byType(属性),contructor(构造函数)

二、默认自动装配(多数装配都是用一样的装配方式,可以全局设定,少数自设定)

 全局byType,MyBean使用constructor

    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
        default-autowire="byType"
        >
    <!-- <bean id="myBean" class="com.lzp.mySpringMin.MyBean" autowire="byName"> 
        </bean> <bean id="myBeanByName" class="com.lzp.mySpringMin.MyBeanByName"></bean> -->

    <bean id="myBean2" class="com.lzp.mySpringMin.MyBean" autowire="constructor">  

    </bean>
    <bean id="myBeanByContructor" class="com.lzp.mySpringMin.MyBeanByContructor"></bean>

三、混合自动装配

    <bean id="myBeanByName" class="com.lzp.mySpringMin.MyBeanByName"></bean>
    <bean id="myBean2" class="com.lzp.mySpringMin.MyBean" autowire="constructor">
        <property name="myBeanByName" ref="myBeanByName"></property>
    </bean>
    <bean id="myBeanByContructor" class="com.lzp.mySpringMin.MyBeanByContructor"></bean>

四、使用注解装配

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context.xsd">
  <!-- <context:component-scan 
      base-package="com.lzp.mySpringMin">
  </context:component-scan> -->
<context:annotation-config></context:annotation-config>

    <!-- <bean id="myBean" class="com.lzp.mySpringMin.MyBean" autowire="byName"> 
        </bean> -->
    <bean id="myBeanByName" class="com.lzp.mySpringMin.MyBeanByName"></bean>
    <!-- <bean id="myBean2" class="com.lzp.mySpringMin.MyBean" autowire="constructor"> -->
    <bean id="myBean2" class="com.lzp.mySpringMin.MyBean" >
        <!-- <property name="myBeanByName" ref="myBeanByName"></property> -->
    </bean>
    <bean id="myBeanByContructor" class="com.lzp.mySpringMin.MyBeanByContructor"></bean>
    <bean id="aa" class="com.lzp.mySpringMin.MyImplatement"></bean>
    <bean id="bb" class="com.lzp.mySpringMin.MyImplatement2"></bean>
    @Autowired
    @Qualifier("aa")
    private MyInterface myInterface;

当一种一个bean时,直接使用@Autowired即可,如果有多个bean为指定同一类型时,可以使用@Qualifier来确定其值。

注意xml的头配置

五、自动扫描

自动扫描在springmvc详细说明。

 

Spring 自动装配