当前位置: 首页 > web >正文

springboot-响应接收与ioc容器控制反转、Di依赖注入

1.想将服务器中的数据返回给客户端,需要在controller类上加注解:@ResponseBody;

这个注解其实在前面已经使用过,@RestController其实就包含两个注解:
@Controller

@ResponseBody

返回值如果是实体对象/集合,将会转换为json格式响应

2.统一响应结果:

如果响应的结果格式不一致,会导致前端处理数据非常麻烦,所以我们可以使用一个result对象来存储响应信息:

3.案例:


 

package new_start.new_start4.controller;import new_start.new_start4.pojo.Emp;
import new_start.new_start4.pojo.Result;
import new_start.new_start4.utils.XmlParserUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;
@RestController
public class EmpController {@RequestMapping("/listEmp")public Result list(){String file = this.getClass().getClassLoader().getResource("emp.xml").getFile();System.out.println(file);List<Emp> empList = XmlParserUtils.parse(file, Emp.class);empList.stream().forEach(emp -> {String gender = emp.getGender();if ("1".equals(gender)) {emp.setGender("男");}else if("2".equals(gender)){emp.setGender("女");}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 new Result(1, "success", empList);}}

但是我们在实际开发中往往使用三层架构:

4.

具体代码:

注意:在service层中需要有一个创建dao对象的步骤:

private EmpDao empdao = new EmpDaoImpl();

同样的在controller层中有一个创建service对象的步骤

private EmpService empService = new EmpServiceImpl();

5.即使这样分层架构,各层之间仍然有耦合性,比如我更改service实现类的名字,那么我就需要在controller层创建对象的时候改代码,这样不利于后期维护;

所以我们需要进行分层解耦,这需要用到控制反转和依赖注入;

我们首先需要将各层实现类进行注解@Component, 将其交给ioc容器,然后使用注解@autowired进行依赖注入

声明bean的时候可以用value来设定bean名,默认为类名首字母小写;

想要声明的bean生效,还需要进行扫描,使用注解@ConponentScan;

但是该注解包含在了启动类声明注解上@SpringBootApplication,扫描范围是所在包及其子包

扫描格式:@ConponentScan({"dao", "com.itheima"}) 小括号包书名号,书名号内写包名,之间用逗号隔开;

6.

@Autowired默认是根据类型进行注入的,如果有多个相同类型的bean,则可以使用@primary进行解决;

或者是@Qualifier

或者是@Resource

http://www.xdnf.cn/news/10486.html

相关文章:

  • nt!MiDispatchFault函数里面的nt!IoPageRead函数分析和nt!MiWaitForInPageComplete函数分析
  • URLDNS利用链剖析
  • latex figure Missing number, treated as zero. <to be read again>
  • mybatis01
  • 3、禁止树莓派屏幕休眠,设置树莓派屏幕常亮
  • VisionPro —— 不规则胶路检测
  • Codeforces Round 1028 (Div. 2) C. Gellyfish and Flaming Peony
  • java synchronized关键字用法
  • STM32Cubemx-H7-17-麦克纳姆轮驱动
  • 关于神经网络中的梯度和神经网络的反向传播以及梯度与损失的关系
  • 用Python打开不同联类型的文件
  • 【xmb】】内部文档148344599
  • 大数据学习(126)-窗口函数范围
  • 通过WiFi无线连接小米手机摄像头到电脑的方法
  • AI炼丹日志-27 - Anubis 通过 PoW工作量证明的反爬虫组件 上手指南 原理解析
  • Java数值处理常见错误解析
  • java多线程与JUC
  • nt!MiDispatchFault函数分析之nt!MiCompleteProtoPteFault函数的作用
  • sqli-labs靶场32-37关(宽字节注入)
  • 历年苏州大学计算机保研上机真题
  • 语音转文字工具
  • Git 入门学习教程
  • Redis 缓存穿透、缓存击穿、缓存雪崩详解与解决方案
  • Ansible 进阶 - Roles 与 Inventory 的高效组织
  • uni-app学习笔记十八--uni-app static目录简介
  • YOLOv5-入门篇笔记
  • 算法打开13天
  • 焦虑而烦躁的上午
  • HTTPS
  • VeriFree:无需Verifier的通用RL框架