【SpringAll】1. Spring 自动注入机制 和 常见注释

Spring 自动注入机制

☀️ @Autowired (常用,最佳方式)

会根据注入的变量名字来寻找合适的 Bean。

⭐ @Qualifier

用于解决注入冲突的,如下例子:

@Component
public class FooExample implenments Example(){
  public String example(){
      return "foo";
  }
}

@Component
public class BarExample implenments Example(){
  public String example(){
      return "bar";
  }
}

@Component
public class FooService(){
// 有注入异常,找不到唯一 Bean
  @Autowired
  private Example example;
}

// todo

如果尝试加载 FooService到上下文,那么会出现 NoUniqueBeanDefinationException。因为 Spring 不确定要注入哪个。

用 @Qualifier 可以解决,如下:

@Component
@Qualifier("fooExample")
public class FooExample implenments Example(){
  public String example(){
      return "foo";
  }
}

@Component
@Qualifier("barExample")
public class BarExample implenments Example(){
  public String example(){
      return "bar";
  }
}

@Component
public class FooService(){
   
// 此时即可唯一指定 Bean
  @Qualifier("fooExample")
  private Example example;
}

@Primary

使用 @Primary 注释的 Bean 总会被默认注入。但 @Qualifier 和 @Primary同时存在,则 @Qualifier > @Primary,因为前者唯一指定了。

@Component
// @Primary 默认注入 FooExample
@Primary
public class FooExample implenments Example(){
  public String example(){
      return "foo";
  }
}

@Component
public class BarExample implenments Example(){
  public String example(){
      return "bar";
  }
}

@Component
public class FooService(){
  @Autowired
  private Example example;
}

@Component

用于标记一个组件,当类不属于@Service、@Controller、@Repository 等,就可以标记该类。

开发常见三件套:

@Controller(注入服务):控制层

@Service(注入dao):服务层

@Repository(实现dao访问):数据访问层

@xxxMapping

为了处理传入请求方法类型而生。

@RequestMapping

最原始方法,有 value,Method两个基本属性。

也可以修饰 xxxController,作为一个地址前缀。

@RequestMapping(value = "/login", method = "RequestMethod.POST")

简化后为:

@PostMapping("/login")

@GetMapping、@PutMapping 同理。

在@GetMapping 或 @PostMapping,左键点进去可以查看源码,了解到 @GetMapping 里面有注释@RequestMapping(method = "Request.GET"),也就是一样的,只是简化了书写而已。

⭐ @GetMapping

获取映射

⭐ @PostMapping

提交映射

☀️ @ResponseBody

将 java 对象转为 JSON 格式的数据。

@RequestMapping + @ResponseBody:本来 @RequestMapping会解析为跳转路径,但加上 @ResponseBody 后则不会。

❗ ❗ ❗ 注意:使用此注解后,不会再走视图处理器,。

  1. @ResponseBody 作用在控制类上,表示该类的所有方法都不会被解析为跳转路径,会直接写在 HTTP Response body上。

  2. @ResponseBody 作用在方法上:返回结果直接写入 HTTP Response Body 中,一般用于 Ajax 异步处理数据时使用。

  3. @ResponseBody 作用在形参上:表示把前端传过来的 (JSON 或 XML 等数据)封装成 Java 对象。

参数注释

接口接受前台的请求参数,可以用 @RequestParam 和 @PathVariable。


当 URL 指向某一具体业务资源(或资源列表) ,用 @PathVariable。

当 URL 需要对资源或资源列表进行筛选时,用 @RequestParam。

用 @RequestParam 时:

1. 若参数不存在:会报出异常。

2. 若参数不一定永远存在,加上参数:

require=false

3. 默认变量值

defaultValue = "0"

合起来就是 @RequestParam(value = "id" require=false defaultValue = "0")

结束语

🏃 Be better than before, never stop thinking!

参考

https://www.cnblogs.com/felordcn/p/12142471.html

https://blog.csdn.net/originations/article/details/89492884

posted @ 2021-09-25 14:53  acchris  阅读(173)  评论(0)    收藏  举报