【注解使用】SpringBoot 注解的使用笔记,持续更新(二)

补缺漏的注解笔记,重点不是基本的注解(例如RequestMapping),当然之后如果有时间会把这一部分的笔记补上去,主要涉及的是使用过程当中遇到的突然的没有见过的注解。

 

1、@RequestParam 和  @PathVariable

@RequestParam

http://localhost:8810/hat?id=1

@PathVariable

http://localhost:8810/user/1

 

 @GetMapping("/user/{id}")
    @ResponseBody
    public String getUser(@PathVariable("id") int id){
        if (id == 1){
            return "野狼disco";
        }else if (id == 2){
            return "情歌王";
        }else {
            return "七里香";
        }
    }


    @GetMapping("/wlh")
    @ResponseBody
    public String getName(){
        return "猪";
    }


    @GetMapping("/hat")
    @ResponseBody
    public String getHatName(@RequestParam("id") int id){
        if(id == 1){
            return  "long";
        }else{
            return  "caihong";
        }
    }

 

这边再补充一些,就是根据阿里巴巴的开发手册,@RequestParam一般用在Controller里头,@Param一般放在dao文件的赋值

 

 

2、@Value

这里的value指的是spring当中的那个value,不是lombok当中的那个。

@Controller
@RequestMapping("hello")
@PropertySource(value = "classpath:/jdbc.properties")
public class ddController {

    @Value("${jdbc.username}")
    private String userName;

    @GetMapping("dd")
    @ResponseBody
    public String getdd(){
       return userName;
    }

}

他可以将propeirties的值引入到代码当中,假如前面没有加@PropertiesSource的话,那么它其实是从application.properties中找的,找不到就报错。

 

拓展:

1、lombok的@value是干嘛用的

https://blog.csdn.net/weixin_41540822/article/details/86606535

 

 

3、@ConditionalOnMissingBean

这个发生在redisTemplate的源码中,它表示假如这个类没有被实例化,那么才会用到以下的这些代码,也就是说,如果有人@bean了这个,那就用它的。通常配合@Bean进行使用

@Bean 
@ConditionalOnMissingBean(name = "redisTemplate") // 我们可以自己定义一个 redisTemplate来替换这个默认的! 
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { 
// 默认的 RedisTemplate 没有过多的设置,redis 对象都是需要序列化! 
// 两个泛型都是 Object, Object 的类型,我们后使用需要强制转换 <String, Object> 
RedisTemplate<Object, Object> template = new RedisTemplate<>(); 
template.setConnectionFactory(redisConnectionFactory); 
return template; 
}

 

4、@SuppressWarnings("")

注解目标为类、字段、函数、函数入参、构造函数和函数的局部变量,用来抑制警告,它后面可以加 all,可以加具体的一些关键字 例如serize等等

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值