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