三层架构
将数据响应,访问,处理的操作分开,使得代码复用性提高,便于维护和扩展。
示例:
//EmpDao接口:
package com.example.dao;
import com.example.pojo.Emp;
import java.util.List;
public interface EmpDao {
public List<Emp> listEmp();
}
//EmpDaoA类:
package com.example.dao.impl;
import com.example.dao.EmpDao;
import com.example.pojo.Emp;
import com.example.utils.XmlParserUtils;
import java.util.List;
public class EmpDaoA implements EmpDao {
@Override
public List<Emp> listEmp() {
String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();
List<Emp> empList = XmlParserUtils.parse(file, Emp.class);
return empList;
}
}
//EmpService 接口:
package com.example.service;
import com.example.pojo.Emp;
import java.util.List;
public interface EmpService {
public List<Emp> listEmp();
}
//EmpServiceA 类:
package com.example.service.Impl;
import com.example.dao.EmpDao;
import com.example.dao.impl.EmpDaoA;
import com.example.pojo.Emp;
import com.example.service.EmpService;
import java.util.List;
public class EmpServiceA implements EmpService {
// 多态,类实现接口,定义接口类型的类,用以实现接口中方法
private EmpDao empDao=new EmpDaoA();
@Override
public List<Emp> listEmp() {
List<Emp> empList=empDao.listEmp();
empList.stream().forEach(emp -> {
String gender = emp.getGender();
if (gender.equals("1"))
emp.setGender("男");
else if (gender.equals("2")) {
emp.setGender("女");
}
String job = emp.getJob();
if (job.equals("1")) {
emp.setJob("讲师");
} else if (job.equals("2")) {
emp.setJob("班主任");
} else if (job.equals("3")){
emp.setJob("就业指导");
}
});
return empList;
}
}
/EmpController类:
import com.example.pojo.Emp;
import com.example.pojo.Result;
import com.example.service.EmpService;
import com.example.service.Impl.EmpServiceA;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class EmpController {
private EmpService empService=new EmpServiceA();
@RequestMapping("/listEmp")
public Result list() {
List<Emp> empList =empService.listEmp();
return Result.success(empList);
}
}
这样就将各个职责分开,逻辑清晰,便于维护管理。
分层解耦
IOC&DI入门
将Service与Dao层的实现对象,交给IOC容器管理。
再为Controller与Service注入运行时依赖的对象。
这样就可以完成层与层之间的解耦。
切记,应将启动类放到所有包外以扫描到所有文件!!
IOC
bean的声明
bean组件扫描
可以使用@ComponentScan来指定扫描的包,但这种方法不推荐,最好还是将启动类放在外层。
DI
bean注入
以上内容均学自b站黑马JavaWeb教学视频