这里用业务类操作Dao类,实现让spring创建一个类包含另一个类的对象
myDao.java
package Ref;
public class myDao implements myDaoInterface {
@Override
public void save(String s) {
// TODO Auto-generated method stub
System.out.println("成功将" + s + "存入数据库");
}
public void p() {
System.out.println("myDao");
}
}
myService.java
package Ref;
public class myService implements myServiceInterface {
private myDaoInterface myD;
public void setMyD(myDaoInterface myD) {
this.myD = myD;
}
@Override
public void work() {
// TODO Auto-generated method stub
myD.save("123");
System.out.println("成功操作了" );
myD.p();
}
}
- 设值注入
<bean id = "myS" class = "Ref.myService">
<property name="myD" ref = "mD"></property>
</bean>
<bean id = "mD" class = "Ref.myDao"></bean>
调用代码
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
myServiceInterface myS = (myService)ac.getBean("myS");
myS.work();
这里要注意ID的对应关系,并且Service类要有对应的set方法
- 构造注入
myService.java
package Ref;
public class myService implements myServiceInterface {
private myDaoInterface myD;
// public void setMyD(myDaoInterface myD) {
// this.myD = myD;
// }
//
public myService(myDaoInterface MYD) {
// TODO Auto-generated constructor stub
this.myD = MYD;
}
@Override
public void work() {
// TODO Auto-generated method stub
myD.save("123");
System.out.println("成功操作了" );
myD.p();
}
}
这里加一个构造函数
xml语句
<bean id = "myS" class = "Ref.myService">
<constructor-arg name = "myD" ref = "mD"></constructor-arg>
</bean>
<bean id = "mD" class = "Ref.myDao"></bean>
这里还是注意名称,myD对应该类的成员变量名。实际操作中用构造函数的参数名MYD也可以实现,调用方式不变
这个例子可以直观的看到好处,业务类接口只提供方法,而业务实现类可以根据需要有自己的private属性,而不影响调用