If you perform the function of class A, B needs to participate in class, we believe that the dependent class B. Class A
2) Document Structure
Establishing a review process for CommentService class business, a DataService class is responsible for interaction with the database. Because the review is to retrieve data from the database, so CommentService class relies DataService class.
-
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();
CommentService public () {}
@Override
public void getById(int id){
System.out.println(dataService.getById(id));
}
@Override
public void the saveData (String STR) {
Boolean In Flag = dataService.saveComment (STR);
IF (== In Flag to true) {
System.out.println ( "Comments saved successfully");
} the else {
System.out.println ( "failed to save comment");
}
}
} -
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 { |
Our function is indeed achieved, but it is not perfect, and therefore leads to the concept of dependency injection, see 7.【读】DI依赖注入
.
Original: Big Box 6. dependencies [read]