DI(重要):依赖注入(Dependency Injection).一般情况下,一个类不可能独立完成一个复杂的业务,需要多个类合作共同完成,需要在类中调用其它类的方法,就要给对象赋值,程序在执行过程中动态给组件(属性)(spring容器实例化并赋予值)赋值,我们把这种赋值方式,叫依赖注入。
(比如在控制层时,定义一个外部类的私有的变量,这是要加@Resource这个注解就是用于依赖注入的,实现接口的实现)
(写实体类,并在spring容器中(配置文件中)赋值对相关属性赋值,这思维不同于面向对象。)
参数值注入
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.sjl.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>