分类 标签 存档 黑客派 订阅 搜索

yml 配置文件使用

295 浏览0 评论

yml配置文件使用

推荐使用yml文件代替默认的properties作为原来配置文件

@ConfigurationProperties(prefix = "girl")

用来注入配置文件中的值,prefix为配置文件中一个属性集合的前缀

例如:
在application.yml中配置这样的属性

girl:
  age: 18
  cupSize: C

然后创建对应的实体类,并添加注解@ConfigurationProperties(prefix = "girl"),注意添加get和set方法


@Component
@ConfigurationProperties(prefix = "girl")
public class GirlBean {
    private int age;
    private String cupSize;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCupSize() {
        return cupSize;
    }

    public void setCupSize(String cupSize) {
        this.cupSize = cupSize;
    }

    @Override
    public String toString() {
        return "GirlBean{" +
                "age=" + age +
                ", cupSize='" + cupSize + '\'' +
                '}';
    }
}

在使用的时候,使用@Autowired注入

 @Autowired
 private GirlBean girlBean;

@RestController

@RestController是Spring4新添加的注解,等同于@Controller和@ResponseBody一起使用的效果

用来处理Http请求,通常添加在类的头部

@RequestParam @PathVariable

这是两种实现自动注入url中的参数值的注解

       @RequestMapping(value = "/hello/{id2}",method = RequestMethod.GET)
        public String say(@RequestParam(value = "id1",required = false,defaultValue = "0") int id1, @PathVariable("id2") int id2){
        return "id1:"+id1+"  id2:"+id2+" "+girlBean.toString();
    }

url可以这样写:

  http://localhost:8081/springbootdemo/hello/1212?id1=111
  • @RequestParam会根据?id1=11来获取参数值
  • @PathVariable则会根据事先设定的{id2}在url中的位置来获取参数值
  • required表示不要求强制添加参数值
  • defaultValue设定未传值时的默认值

@GetMapping @PostMapping...

这是一些组合注解,例如@GetMapping等同于@RequestMapping(value = "",method = RequestMethod.GET)

评论  
留下你的脚步
推荐阅读