前文要修改web service的默认端口,用到了application.properties。而实际上,application.properties的功能远不止于此。
配置服务参数
在application.properties文件中输入下面的代码、保存,可以修改应用的名字和服务端口。
spring.application.name=not-hello-world
server.port=8080
实际上,除了这些貌似没有太大实用价值的配置参数外,application.properties还可以配置程序要用到的具体参数,如数据库用户名、密码:
datasource.master.username=root
datasource.master.password=1234
定义变量在application.properties里面定义变量
customer.name=Bruce Lee
2. 在代码中使用注解@Value引用变量
@Value("${customer.name}")
private String customer;
至此,字符串‘Bruce Lee’就被赋值给了变量customer。接下来,在第一篇中的“/hello”中打印customer
@RequestMapping("/hello")
public String hello() {
return "hello " + customer;
}
3. 访问api查看结果
重启service,打开http://localhost:8080/hello,能看到返回结果变成了:
hello Bruce Lee
参数之间的引用
application.properties的内部参数之间还可以相互引用,如:
customer.firstname=Bruce
customer.lastname=Lee
customer.name=${customer.firstname}-${customer.lastname}
重启service,打开http://localhost:8080/hello,能看到返回结果变成了:(“Bruce”和“Lee”之间的空格变成了减号)
hello Bruce-Lee
通过命令行参数修改application.properties的参数值
前文中曾经提到通过jar启动web service,实际上通过添加命令行参数,还可以重新定义变量。如,按照下面的命令启动web service:
mvn clean package
java -jar target/helloworld-0.0.1-SNAPSHOT.jar --customer.firstname=Jet
打开http://localhost:8080/hello,能看到返回结果变成了:
hello Jet-Lee
其他用法
实际上,还可以在application.properties中生成一些随机数,比如:生成一个各学龄的学生的年龄。
student.age.beforeschool=${random.int(6)}
student.age.primaryschool=${random.int(6, 12)}
student.age.middleschool=${random.int[12, 18]}
然后可以在代码中用@Value引用变量
@Value("${student.age.beforeschool}")
private int age;