在SpringBoot创建项目成功启动之后,可以发现在resources下面是没有XML文件的,只有一个application.properties配置文件,这是因为Spring Boot “约定优于配置”。所以想要懂得如何开启各个功能模块的默认配置,这就需要了解Spring Boot的配置文件application.properties。
例如: 在配置文件中设置端口和项目路径 如下图所示
在启动日志当中可以看到:
自定义属性的读取
可以在配置文件当中配置一些自定义属性,在项目当中进行读取。例如:
在配置文件application.properties 添加属性
application.age=18
application.name=jake
然后创建一个类,将配置属性封装到类当中。@ConfigurationProperties(prefix=”application”),标明识别的是前缀为application的属性。
@Component
@ConfigurationProperties(prefix = "application")
public class MyProperties1 {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "MyProperties1{" + "age=" + age + ", name='" + name + ''' + '}';
}
}
然后通过一个controller自动注入这个类
@RequestMapping("/properties")
@RestController
public class PropertiesController {
@Autowired
private MyProperties1 myProperties1;
@GetMapping("/1")
public MyProperties1 myProperties1() {
return myProperties1;
}
}
最后效果图如下:
自定义属性的获取也可以使用 @Value注解方式 这种相对方便灵活 例如:只需要在controller里面直接注入就可以了。
@RestController
public class PropertiesController {
@Value("${application.name}")
private String name;
@Value("${application.age}")
private String age;
@RequestMapping("/value")
public String hexo(){
return name+","+age;
}
自定义配置文件
有时不想所有属性写在一个配置文件当中,需要使用自定义配置文件
1. 新建一个my.properties中属性为
my.test1=123456789
my.test2=vip
2.使用@ProertySouce
注解,标明使用哪个配置文件
@Component
@ConfigurationProperties(prefix="my")
@PropertySource(value={"classpath:my.properties"})
public class ApplicationProperties {
private String test1;
private String test2;
public String getTest1() {
return test1;
}
public void setTest1(String test1) {
this.test1 = test1;
}
public String getTest2() {
return test2;
}
public void setTest2(String test2) {
this.test2 = test2;
}
}
3.使用
@Resource
private ApplicationProperties applicationProperties;
多环境化配置
多元化环境的配置可以使用Spring.profile.active 这个实现。格式为:application-{profile}.properties
profile 是自定义的,其他的不能变。 例如:在开发,测试,使用当中使用不同的数据库时。配置信息一直改,不方便时。
Spring.profile.active =test1 就会引入配置文件application-test1.properties