spring总结之三(依赖注入)

DI(重要):依赖注入(Dependency Injection).一般情况下,一个类不可能独立完成一个复杂的业务,需要多个类合作共同完成,需要在类中调用其它类的方法,就要给对象赋值,程序在执行过程中动态给组件(属性)赋值,我们把这种赋值方式,叫依赖注入。

(写实体类,并在配置文件中对相关属性赋值,这思维不同于面向对象。)

参数值注入

bean对象 ref
基本数据类型和字符串
各种类型的集合list set map Properties
public class ValueBean {
private String name;
private Integer age;
private List<String> like;
private Set<String> city;
private Map<String,Object> student;
private Properties db;
public void setName(String name) {
    this.name = name;
}
public void setAge(Integer age) {
    this.age = age;
}
public void setLike(List<String> like) {
    this.like = like;
}
public void setCity(Set<String> city) {
    this.city = city;
}
public void setStudent(Map<String, Object> student) {
    this.student = student;
}
public void setDb(Properties db) {
    this.db = db;
}
@Override
public String toString() {
    return "ValueBean [name=" + name + ", age=" + age + ", like=" + like + ", city=" + city + ", student=" + student
            + ", db=" + db + "]";
}

}

  

<!-- 给各种类型的参数依赖注入 -->
 <bean id="valueBean" 
       class="cn.tedu.spring.bean.ValueBean">
     <property name="name" value="王影"/>
     <property name="age" value="18"/>
     <property name="like">
        <list>
            <value>旅游</value>
            <value>电视剧</value>
            <value>听音乐</value>
        </list>
     </property>
     <property name="city">
        <set>
            <value>沈阳市</value>
            <value>大连市</value>
            <value>鞍山市</value>
        </set>
     </property>
   <property name="student">
        <map>
            <entry key="name" value="贾宝飞"/>
            <entry key="age" value="18"/>
            <entry key="phone" value="13800138000"/>
        </map>
     </property>
     <property name="db">
        <props>
            <prop key="driverClassName">com.mysql.jdbc.Driver</prop>
            <prop key="url">jdb:mysql://localhost:3306/dbName</prop>
            <prop key="username">root</prop>
            <prop key="password">root</prop>
        </props>
     </property>
 </bean>
 

猜你喜欢

转载自www.cnblogs.com/shijinglu2018/p/9563411.html
今日推荐