Spring依赖注入

通过构造函数注入

<bean id="accountDao" class="com.ttpfx.dao.impl.AccountDaoImpl"/>
<bean id="accountService" class="com.ttpfx.service.impl.AccountServiceImpl">
    <constructor-arg name="accountDao" ref="accountDao"/>
</bean>

通过set方法注入

<bean id="accountDao" class="com.ttpfx.dao.impl.AccountDaoImpl"/>
<bean id="accountService" class="com.ttpfx.service.impl.AccountServiceImpl">
   <property name="accountDao" ref="accountDao"/>
</bean>

注入基本类型、String、Bean

public class Account {
    private Integer id;
    private String username;
    private Date birthday;
}
<bean id="now" class="java.util.Date"/>
<bean id="account" class="com.ttpfx.domain.Account">
    <property name="id" value="1"/>
    <property name="username" value="张三"/>
    <property name="birthday" ref="now"/>
</bean>  

注入集合

public class JavaCollection {
    private String[] array;
    private List<String> list;
    private Set<String> set;
    private Map<String, String> map;
    private Properties properties;
}
<bean id="javaCollection" class="com.ttpfx.domain.JavaCollection">
    <property name="array">
        <array>
            <value>张三</value>
            <value>李四</value>
            <value>王五</value>
            <value>赵六</value>
        </array>
    </property>
    <property name="list">
        <list>
            <value>one</value>
            <value>two</value>
            <value>three</value>
            <value>four</value>
        </list>
    </property>
    <property name="set">
        <set>
            <value>北</value>
            <value>上</value>
            <value>广</value>
            <value>深</value>
        </set>
    </property>
    <property name="map">
        <map>
            <entry key="one" value="一"/>
            <entry key="two" value="二"/>
            <entry key="three" value="三"/>
        </map>
    </property>
    <property name="properties">
        <props>
            <prop key="1">一</prop>
            <prop key="2">二</prop>
            <prop key="3">三</prop>
        </props>
    </property>
</bean>
posted @ 2021-03-17 18:28  ttpfx  阅读(49)  评论(0编辑  收藏  举报