springboot分层解耦

发布时间 2023-09-27 21:11:57作者: 傲世小苦瓜

软件开发需要符合“高内聚低耦合”的特性,所以需要将程序分为三层

即:

 使每一层各司其职,增加软件的复用性,使其更加便于维护,利于扩展。

controller层:

package com.wmx.controller;


import com.wmx.dao.EmpDao;
import com.wmx.dao.impl.EmpDaoA;
import com.wmx.pojo.Emp;
import com.wmx.pojo.Result;
import com.wmx.service.EmpService;
import com.wmx.service.impl.EmpServiceA;
import com.wmx.utils.XmlParserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class EmpController { @Autowired//运行时,IOC容器会提供该类型的bean对象,并赋值给该变量 - 依赖注入 private EmpService empService ; @RequestMapping("/listEmp") public Result list(){ List<Emp> empList = empService.listEmp(); //3、响应数据 return Result.success(empList); } }

dao层:

package com.wmx.dao.impl;

import com.wmx.dao.EmpDao;
import com.wmx.pojo.Emp;
import com.wmx.utils.XmlParserUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Component //将当前类交给IOC容器,成为IOC容器的bean
public class EmpDaoA implements EmpDao {

    @Override
    public List<Emp> listEmp() {
        //1加载并解析xml文件
        String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();
        System.out.println(file);
        List<Emp> empList = XmlParserUtils.parse(file, Emp.class);

        return empList;
    }
}

service层:

package com.wmx.service.impl;

import com.wmx.dao.EmpDao;
import com.wmx.pojo.Emp;
import com.wmx.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component//将当前类交给IOC容器,成为IOC容器的bean
public class EmpServiceA implements EmpService {
    @Autowired//运行时,IOC容器会提供该类型的bean对象,并赋值给该变量 - 依赖注入
    private EmpDao  empDao ;
    @Override
    public List<Emp> listEmp() {
        //1、调用dao,获取数据
        List<Emp> empList = empDao.listEmp();
        //2、对数据进行转换处理
        empList.stream().forEach(emp -> {
            //处理 gender 1:男 2:女
            String gender = emp.getGender();
            if("1".equals(gender)){
                emp.setGender("男");
            }
            else if("2".equals(gender)){
                emp.setGender("女");
            }

            //处理job
            String job = emp.getJob();
            if("1".equals(job)){
                emp.setJob("讲师");
            }
            else if("2".equals(job)){
                emp.setJob("班主任");
            }
            else if("3".equals(job)){
                emp.setJob("就业指导");
            }
        });

        return empList;
    }
}