如果类A的功能的执行需要类B的参与,我们就认为类A依赖类B。
2) 文档结构
建立一个CommentService类用来处理评论的业务,一个DataService类来负责与数据库的交互。因为评论是从数据库里取出数据的,所以CommentService类依赖DataService类。
-
src
-
com.spring4
-
inter
-
ICommentService
1
2
3
4public interface ICommentService {
void getById(int id);
void saveData(String str);
} -
IDataService
1
2
3
4public interface IDataService {
String getById(int id);
boolean saveComment(String str);
}
-
-
service
-
CommentService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20public class CommentService implements ICommentService {
public IDataService dataService = new DataService();
public CommentService(){}
@Override
public void getById(int id){
System.out.println(dataService.getById(id));
}
@Override
public void saveData(String str){
boolean flag = dataService.saveComment(str);
if(flag == true){
System.out.println("评论保存成功");
}else{
System.out.println("评论保存失败");
}
}
} -
DataService
1
2
3
4
5
6
7
8
9
10
11public class DataService implements IDataService {
@Override
public String getById(int id){
return "这是第"+id+"条评论";
}
@Override
public boolean saveComment(String str){
return true;
}
}
-
-
Application
1
2
3
4
5
6
7
8public class Application {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
ICommentService commentService = (ICommentService) applicationContext.getBean("commentService");
commentService.getById(22);
commentService.saveData("JPA教程..");
}
}
-
-
beans.xml
1
2
3
4
5
6
7
8<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="commentService" class="com.spring4.service.CommentService" >
</bean>
</beans>
-
3) 结果分析
运行输出结果为
我们使用到了DataService这个bean,但是我们在beans.xml文档中没有对这个bean进行配置。因此不能通过getBean(“标识”)来获取实例,所以我们通过new操作来获取这个bean的实例。
1 |
public class CommentService implements ICommentService { |
我们的功能确实是实现了,但是它却不够完美,因此引出依赖注入的概念,详见7.【读】DI依赖注入
。