SpringBoot默认会去加载一个应用程序配置文件,文件名为application,有两种样式的配置文件如下:
一、application.properties 配置文件
配置文件内容如下:
server.port=8888 server.servlet.context-path=/cfg names=xiaomage,haha,zhangsan,lisi homes={'bj':'daxing', 'sh':'huangpujiang'}
测试类:
package com.mj.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.Map; @RestController public class TestController { @Value("${names}") private String[] names; @Value("#{${homes}}") private Map<String, String> homes; @RequestMapping("/test") public String test() { for (String name : names) { System.out.println(name); } homes.forEach((k, v) -> { System.out.println(k + "_" +v); }); return "test!!!!" ; } }
二、application.yml 配置文件
pom.xml文件新增两个依赖;
<!--自动生成set get 和tostring方法,不过需要下载插件才有提示--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--ynl 里面有提示信息 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency>
yml配置文件如下:
domain类的配置如下:
非构造方法绑定:
@Component @ConfigurationProperties("cat") @Data public class Cat { private String name; private Integer age; private Integer id; private String[] nickNames; }
构造方法绑定:
@ConfigurationProperties("student") @ConstructorBinding @Data public class Student { private Integer id; private String name; public Student(Integer id, String name) { this.id = id; this.name = name; } }
测试类:
@EnableConfigurationProperties(Student.class) @RestController public class TestController { @Autowired private Person person; @Autowired private Dog dog; @Autowired private Cat cat; @Autowired private Student student; @RequestMapping("/test1") public String test1() { return "test1!!!"; } @RequestMapping("/test2") public String test2() { System.out.println(person); return "test2!!!"; } @RequestMapping("/test3") public String test3() { System.out.println(dog); return "test3!!!"; } @RequestMapping("/test4") public String test4() { System.out.println(cat); return "test4!!!"; } @RequestMapping("/test5") public String test5() { System.out.println(student); return "test5!!!"; } }