美文网首页
springBoot-03-配置文件[一]2018-09-01

springBoot-03-配置文件[一]2018-09-01

作者: 青山有扶苏 | 来源:发表于2018-09-01 23:47 被阅读0次
    当你认为最美好的事情,可能在别人眼里不值一提  
    你认为简单而又不起眼的 ,可能别人背后付出了百倍的艰辛
    

    开始:
    在一般项目开发中,通常我们会把数据库配置,短信发送的Key配置,定时任务的配置等等,都放到properties文件中,以方便后续更改。 所以配置文件在实际开发中,也是非常常用的。所以,我也趁机看了一下SpringBoot中的配置文件。

    目前有两种类型的,一个是存在于 application.yml[或者properties]另外一种是,其他自定义的配置文件。

    首先,看看application.yml文件
    1.如果读取配置文件 application.yml的属性,只需要在读取的地方,添加一个成员变量,成员变量上添加 @Value("xxx")的注解,例如

    @RestController
    public class HelloController {
        
        @Value("${user.name}")
        private String name;
        @Value("${user.age}")
        private int age;
    }
    

    2.我们也可以将配置文件中某个根下的属性读取到一个实体类中,例如
    配置文件的内容

    user: 
      name: bywinkey
      age: 18 
      number: ${random.int}
      uuid: ${random.uuid}
    

    然后在要承接属性的实体类中添加

    @ConfigurationProperties(prefix = "user")
    @Component
    

    后面这个 prefix ="xxx" 其实就是配置文件中的 user {根的名字}
    实体类中的成员变量名称只要和配置文件中的名字保持一致即可

    @ConfigurationProperties(prefix = "user")
    @Component
    public class YmlProperty {
        
        private String name;
        private int age;
        private int number;
        private String uuid;
            //...geter/seter
    }
    

    3.有时候,需要将配置文件单独一个文件中出来,因此就不能用默认的application.yml的方法读取了,需要这样做,例如我们在resources目录下创建一个 myconf.properties文件内容如下

    frend.email=1020952183@qq.com
    frend.telephone=135****1134
    

    实体类中需要指明文件的路径及文件名,因此需要多一个这样的配置

    @PropertySource("classpath:myconf.properties")
    

    注解里面的内容,就是我们要读取的配置文件的路径和名称
    类文件如下

    @Configuration
    @PropertySource("classpath:myconf.properties")
    @ConfigurationProperties(prefix = "frend")
    public class GlobalProperties {
    
        private String email;
        
        private String telephone;
            //...geter/seter
    }
    

    使用方法也很简单,只需要在使用的地方用
    @Autowired 注入就可以了

    @Autowired
    private GlobalProperties properties;
    

    我就先总结这几种方式,后续有遇到其他有趣的写法的,我会在主键的加进来。
    这里配置好之后,在前面几篇的项目基础上运行,测试和预期结果一样就表示你运行成功了。
    大家加油

    相关文章

      网友评论

          本文标题:springBoot-03-配置文件[一]2018-09-01

          本文链接:https://www.haomeiwen.com/subject/iirpwftx.html