Dependency Injection,中文名依赖注入。说白了就是在bean对象外部给bean对象内部的元素赋值。
代码:
public class ServiceImpl implements UserService {
private UserDao user;//待赋值
private int num;
private String name;
private Map<String,String> map;
//对于普通数据用什么方法都行,注意setXXX方法的XXX对应数据名
public void setName(String name) {
this.name = name;
}
public void setNum(int num) {
this.num = num;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
@Override
public void save() {
System.out.println("依赖注入");
//user.save();
System.out.println(name+num);
System.out.println(map.get("1"));
System.out.println(map.get("2"));
}
//set方法、p命名空间注入,两者本质上一样
/*public void setUserDao(UserDao userDao) {
this.user = userDao;
}*/
//构造体注入对象
public ServiceImpl(UserDao user) {
this.user = user;
}
public ServiceImpl() {
}//空构造体
}
public class DITest {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//UserService s = (UserService) app.getBean("DI_set方法注入");
//UserService s = (UserService) app.getBean("DI_p命名空间注入");
//UserService s = (UserService) app.getBean("DI_构造体方法注入");
UserService s = (UserService) app.getBean("DI_普通数据注入赋值");
s.save();
}
}
配置文件:
property:所有物、性质;顾名思义,此标签用于给bean对象中各种元素赋值;
name=元素名;
value=想赋的值;
ref=引用,为对象赋值需引用现成对象;
value-ref=当想赋的值为对象时需引用现成对象;
constructor-arg ref=有参构造体中参数为对象时,引用现成对象。
<!--<bean id="DI_set方法注入" class="III_DI依赖注入.Impl.ServiceImpl" >
<property name="userDao" ref="UserDaoI"></property>
</bean>-->
<!--<bean id="DI_p命名空间注入" class="III_DI依赖注入.Impl.ServiceImpl" p:userDao-ref="UserDaoI"></bean>-->
<!--<bean id="DI_构造体方法注入" class="III_DI依赖注入.Impl.ServiceImpl">
<constructor-arg ref="UserDaoI"></constructor-arg>
</bean>-->
<bean id="DI_普通数据注入赋值" class="III_DI依赖注入.Impl.ServiceImpl" >
<property name="num" value="666"></property>
<property name="name" value="Kvno"></property>
<property name="map">
<map>
<entry key="1" value="神说:"></entry>
<entry key="2" value="要有光"></entry>
</map>
</property>
</bean>