1. 程式人生 > >Spring入門(一):Spring注入

Spring入門(一):Spring注入

概念

Spring注入是指在啟動Spring容器載入bean配置的時候,完成對變數的賦值行為

常用的兩種注入方式

  • 設值注入
  • 構造注入

設值注入

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >

    <bean id="injectionService" class="com.imooc.ioc.injection.service.InjectionServiceImpl">
        <property name="injectionDAO" ref="injectionDAO"></property>
    </bean>
    
    <bean id="injectionDAO" class="com.imooc.ioc.injection.dao.InjectionDAOImpl"></bean>

</beans>

成員變數injectionDAO,型別是InjectionAOImpl,引用bean injectionDAO

構造注入

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >

    <bean id="injectionService" class="com.imooc.ioc.injection.service.InjectionServiceImpl">
    <constructor-arg name="injectionDAO" ref="injectionDAO"></constructor-arg>
    </bean>

    <bean id="injectionDAO" class="com.imooc.ioc.injection.dao.InjectionDAOImpl"></bean>

</beans>