springboot 配置文件
1、工程结构
2、启动类ApplicationDemo
package com.cmsz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import com.cmsz.config.PrivilegeSettings;
//加载默认的配置
@SpringBootApplication
//加载自己的配置类
@EnableConfigurationProperties({PrivilegeSettings.class})
public class ApplicationDemo{
public static void main(String[] args){
SpringApplication.run(ApplicationDemo.class, args);
}
}
3、配置类
package com.cmsz.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
//配置类上写明自己的配置文件路径classpath:/config/myapplication.properties
@ConfigurationProperties(prefix="privilege", locations = "classpath:/config/myapplication.properties")
public class PrivilegeSettings {
private String superman;
private String assistor;
private String admin;
//getter and setter
}
4、测试类
package com.cmsz.control;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cmsz.config.PrivilegeSettings;
@RestController
public class TestController {
@Autowired
private PrivilegeSettings privilegeSettings ;
@Value("${name}")
private String firstName;
@RequestMapping(value="/test")
public String test(){
System.out.println(privilegeSettings.getAdmin());
System.out.println(privilegeSettings.getAssistor());
System.out.println(firstName);
return "ok";
}
}
5、重点:配置文件的位置
默认加载resource路径下的appilication.properties
如果还有其他的配置文件,可以在resource目录下新建config文件夹,编写自己的配置文件myapplication.properties
6、配置文件的注解配置:
//加载默认的配置
@SpringBootApplication
//加载自己的配置类
@EnableConfigurationProperties({PrivilegeSettings.class})
//配置类上写明自己的配置文件路径classpath:/config/myapplication.properties
@ConfigurationProperties(prefix="privilege", locations = "classpath:/config/myapplication.properties")