1. 概述
Spring最主要的思想是IoC(Inversion of Control, 控制反转、反向控制),或者称为DI(Dependency Injection,依赖注入)。
2. 创建spring项目
创建spring项目,会在src目录下生成applicationContext.xml文件。如果没有,自己建个xml文件,文件名称自己定。
若创建是web项目,则添加spring包;若创建是maven项目,则需在Pom.xml中添加spring依赖,如下:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.0.0.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
3. 编写类
3.1. 实体类
public class Student {
private int id;
private String name;
//set、get方法
}
3.2 DAO层
- IDao定义一个得到学生信息的方法
public interface IDao {
// 得到学生的信息
public String getStuInfo();
}
- DaoImpl实现IDao接口,DaoImpl类用到Student类
public class DaoImpl implements IDao{
private Student student;
@Override
public String getStuInfo() {
return "id:"+student.getId() + " name:" + student.getName();
}
//student的get、set方法
}
3.3 Service层
- IService定义方法,打印学生信息
public interface IService {
//打印学生信息
public void printStuInfo();
}
- ServiceImpl实现IService接口,ServiceImpl类用到Dao类
public class ServiceImpl implements IService{
private IDao dao;
@Override
public void printStuInfo() {
System.out.println(dao.getStuInfo());
}
//dao的set、get方法
}
4. 编写配置文件applicationContext.xml
- 配置student bean,并赋值。class是Student类所在的路径。配置student bean相当于创建了一个student对象
<bean id="student" class="com.springxml.Student">
<property name="id" value="123456"/>
<property name="name" value="zhangsan"/>
</bean>
- 配置daoImpl bean。property标签,name值对应DaoImpl里的student成员,ref指向 student bean,ref的值为配置student bean的id。相当于在daoImpl代码中执行
student = new Student();
<bean id="dao" class="com.springxml.DaoImpl">
<property name="student" ref="student"/>
</bean>
- 配置serviceImpl bean。相当于在serviceImpl代码中执行
dao = new DaoImpl();
<bean id="service" class="com.springxml.ServiceImpl">
<property name="dao" ref="dao"/>
</bean>
5.运行测试
- 新建Java类,运行测试。
public class MyMain {
public static void main(String[] args) {
//读取配置文件
AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//获得bean
IService service = (IService)context.getBean("service");
service.printStuInfo();
}
}
- 打印出结果,运行成功
id:123456 name:zhangsan
源码:
https://gitee.com/LuckZ/spring-xml-annotation-demo
https://github.com/LuckZZ/spring-xml-annotation-demo