前言
spring-boot有一个优点是:习惯优于配置。说明spring boot有很多的配置,所以今天我们学习它的配置文件:application.properties
。
正文
Spring Boot有一个全局的配置文件:application.properties
,放在src/main/resources
目录下,我们一起来学习一下它吧。
一,自定义属性
在application.properties
文件中我们可以自定义属性:
com.mlin.name="mlin"
com.mlin.dream="想吃美食"
在需要读取的地方通过@Value(value="${config.name}")
的方式读取:
@RestController
public class UserController {
@Value("${com.mlin.name}")
private String name;
@Value("${com.mlin.dream}")
private String dream;
@RequestMapping("/proper")
public String getProper(){
return name+","+dream;
}
}
运行启动文件,浏览器输入:http://localhost:8080/proper
,看到如下画面:

这是一种读取配置文件属性的方式,可以看出还是比较麻烦的,因为一旦属性过多,那一个个的配置真的挺繁琐。接下来讲第二种方式:
新建实体文件:
Config.java
,添加注解:@ConfigurationProperties(prefix = "com.dudu")
,指明要引用的属性
@ConfigurationProperties(prefix = "com.mlin")
public class Config {
private String name;
private String dream;
//get and set
}
spring Boot入口类:Chapter1Application
加上@EnableConfigurationProperties({Config.class})
注解,指明要加载的bean文件:
@SpringBootApplication
@EnableConfigurationProperties({Config.class})
public class Chapter1Application {
public static void main(String[] args) {
SpringApplication.run(Chapter1Application.class, args);
}
}
最后在要读取属性的地方引用bean文件即可:
@RestController
public class UserController {
@Autowired
Config config;
@RequestMapping("/proper1")
public String getProper1(){
return config.getName()+config.getDream();
}
}
在application.properties
中的各个参数之间还可以组合,成为新的属性,如:
com.mlin.name="mlin"
com.mlin.dream="想吃美食"
com.mlin.mydream=${com.mlin.name}的愿望是${com.mlin.dream}
二,自定义配置文件
有时候我们不想把所有的配置文件都放在application.properties
,因此我们可以自己创建配置文件,这里创建了mlin.properties
,同样放在src/main/resourses
下面:
com.mlin.name="mlin"
com.mlin.dream="想吃美食aaa"
com.mlin.mydream=${com.mlin.name}的愿望是${com.mlin.dream}
创建bean文件ConfigTest.java
,添加注解如下所示:
@Configuration
@ConfigurationProperties(prefix = "com.mlin")
@PropertySource("classpath:mlin.properties")
public class ConfigTest {
private String name;
private String dream;
//set and get
}
和读取application.properties
配置文件最大的区别就在于读取自定义的配置文件需要@Configuration
和@PropertySource("classpath:mlin.properties")
两个注解指定要读取的配置文件,其他的方法一样。
三,随机配置
还可以在配置文件中使用${random} 来生成各种不同类型的随机值,如:
com.mlin.number=${random.int}
com.mlin.secret=${random.value}
com.mlin.bignumber=${random.long}
com.mlin.uuid=${random.uuid}
com.mlin.number.less.than.ten=${random.int(10)}
com.mlin.number.in.range=${random.int[1024,65536]}
原创作者:梦凌小样
作品链接:https://www.jianshu.com/p/70cb387deb05【原创不易,转载请注明出处,感谢理解】
一位爱生活,爱创作,爱分享,爱自己的90后女程序员一枚,记录工作中的点点滴滴,一起学习,共同进步,期待能和优秀的您交上朋友
网友评论