一、区别
二、说明
三、实战
1、@Autowired 按类型匹配。
A、定义了接口
1 package com.yzc.springMVC.service; 2 3 /** 4 * 5 * @Title: AutowiredController.java 6 * @Package: com.yzc.springMVC 7 * @Description: 描述该文件做什么 8 * @author yangzhancheng 9 * @2020年4月19日:下午10:39:55 10 * 11 */ 12 13 public interface IAutowiredService { 14 15 String action(); 16 }
B、一个实现类
1 package com.yzc.springMVC.service; 2 3 import org.springframework.stereotype.Service; 4 5 /** 6 * 7 * @Title: AutowiredServiceOne.java 8 * @Package: com.yzc.springMVC.service 9 * @Description: 按类型进行注解 10 * @author yangzhancheng 11 * @2020年4月19日:下午10:56:42 12 * 13 */ 14 @Service 15 public class AutowiredServiceTYPE implements IAutowiredService{ 16 17 public String action(){ 18 String msg = "AutowiredServiceTYPE:是按类型。"; 19 return msg; 20 } 21 }
C、Controller 类中根据类型自动匹配
1 package com.yzc.springMVC.controller; 2 3 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.ResponseBody; 8 9 import com.yzc.springMVC.service.IAutowiredService; 10 11 12 /** 13 * 14 * @Title: AutowiredController.java 15 * @Package: com.yzc.springMVC 16 * @Description: 描述该文件做什么 17 * @author yangzhancheng 18 * @2020年4月19日:下午10:39:55 19 * 20 */ 21 @Controller 22 @RequestMapping(value = "/autowired") 23 public class AutowiredController { 24 25 /** 26 * 通过类自动匹配 27 */ 28 @Autowired 29 private IAutowiredService autowiredService; 30 31 @RequestMapping(value = "/action",produces = "application/json;charset=UTF-8") 32 @ResponseBody 33 public String action(){ 34 String msg = autowiredService.action(); 35 System.out.print(msg); 36 return msg; 37 } 38 39 40 }
E、运行结果