属性注入方式

  1. spring支持的注入方式:
    (1)set注入方式
    (2)有参注入方式

  2. 具体实现
    有参注入方式:

<bean id="bean" class="com.psn.spring.property.PropertyDemo">
        <constructor-arg name="username" value="xiaowang">constructor-arg>
bean>

set注入方式(*):

1.字符串属性注入

<bean id ="bean" class="com.psn.spring.property.Book">
 <property name="name" value="hehe">property>
bean>

2.对象类型注入
UserDao.java

public class UserDao {
    public void add()
    {
        System.out.println("userdao...........");
    }
}

UserService.java

public class UserService {

    UserDao userdao;

    public void setUserdao(UserDao userdao) {
        this.userdao = userdao;
    }

    public void add()
    {
        System.out.println("userservice...........");
        userdao.add();
    }
}

applicationContext.xml

<bean id="userDao" class="com.psn.spring.property.UserDao">bean>

<bean id="userservice" class="com.psn.spring.property.UserService">
            <property name="userdao" ref="userDao">property>
bean>

3.复杂属性注入

    //复杂属性
    private String[] arrs;
    private List list;
    private Map map;
    private Properties properties;


  <bean id="person" class="com.psn.spring.property.Person">
    <property name="arrs" >
        
        <array>
            <value>xiaowangvalue>
            <value>xiaomavalue>
            <value>wangervalue>
        array>
    property> 

    <property name="list">
        <list>
            <value>xiaowangvalue>
            <value>xiaomavalue>
            <value>wangervalue>
        list>
    property>

    <property name="map">
        <map>
            <entry key="aa" value="aa">entry>
            <entry key="bb" value="bb">entry>
            <entry key="cc" value="cc">entry>
        map>
    property>
    <property name="properties">
        <props>
            <prop key="driverclass">com.mysql.jdbc.Driverprop>
            <prop key="username">rootprop>
        props>
    property>
 bean>

你可能感兴趣的:(Spring)