玩转SpringBoot

来源:互联网 发布:mac双系统移除win8后 编辑:程序博客网 时间:2024/06/05 08:50

玩转SpringBoot - 02 自定义配置文件

  • 玩转SpringBoot - 02 自定义配置文件
    • SpringBoot 配置文件
    • 自定义配置信息获取

1. SpringBoot 配置文件

SpringBoot 配置文件默认文件名为application,分为两种格式文件

  • application.properties
    默认配置方式为:
server.port = 8080
  • application.yml
    默认配置方式为:
server:    port:      8080

文件默认存在于src/main/resources 目录下,当项目启动时,会自动扫描目录下的改文件,读取文件中的配置。

官方文档最全配置信息地址:点击此处


2. 自定义配置信息获取

有的时候,我们需要获取一些自定义的参数,如连接池的连接信息,此时此刻不想添加其他配置文件,我们可以通过获取application 配置文件中自定义的参数。
1. 使用@Value 注解
这种方法,估计很多同学都是会的,以properties 类型举例子。
现有自定义配置的信息如下:

test.username = user1test.password = pass1

那么我们在项目中,可以如此获取以上属性:

@Value(name = "test.username")String username;@Value(name = "test.password")String password;

输入键值对的key,就可以获取到属性。
那么如果我们自定义的属性太多,就不太适合这样的注入方式了,所以有了以下注解。
2. 使用@ConfigurationProperties 注解
我们只需要新建一个类,比如:

@Component@ConfigurationProperties(prefix = "test")public class TestProperty{    String username;    String password;    // 省略getter & setter}

在启动类上加上@EnableConfigurationProperties 注解即可打开此功能,如果新建的类与main 的类不在同一目录下,那么需要指定一个Class[] 属性,以下为源码部分片段:

public @interface EnableConfigurationProperties {  Class<?>[] value() default {};}

在使用的时候,直接使用@Autowired 注解进行注入即可:

@AutowiredTestProperty testProperty;

其他内容等待

原创粉丝点击