一、配置文件加載
1、Controller中配置並指向文件
@Controller @PropertySource(value = { "application.properties" })//指定配置文件
2、在變量上打注解並指明配置文件中的key
@Value("${web.upload.filepath}")//獲取配置文件中的配置參數 private String filePath;
二、實體類配置文件
1、添加@Component//文件掃描注解
2、使用@PropertySource({"classpath:jdbc.properties"}) //指定配置文件的位置
3、使用@ConfigurationProperties 或者 @ConfigurationProperties(prefix="jdbc")//前綴,設置相關的屬性;
4、使用@Autowired//通過IOC對象自動注入
示例-新建實體類如下:
package cn.xiaobing.demo.pojo; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component//文件掃描 @PropertySource({"classpath:jdbc.properties"}) //@ConfigurationProperties @ConfigurationProperties(prefix="jdbc")//前綴 public class JDBCSettings { //@Value("${jdbc.driver}") //如果屬性命名和配置文件中配置name一致就不需要聲明@Value("${jdbc.driver}") private String driver; private String url; private String username; private String password; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public JDBCSettings(String driver, String url, String username, String password) { super(); this.driver = driver; this.url = url; this.username = username; this.password = password; } public JDBCSettings() { super(); } @Override public String toString() { return "JDBCSetting [driver=" + driver + ", url=" + url + ", username=" + username + ", password=" + password + "]"; } }
jdbc.properties文件配置信息
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/future?useUnicode=true&characterEncoding=utf-8 jdbc.username=Administrator1 jdbc.password=123456
Controller編碼
@RestController public class GetController { @Autowired//通過IOC對象自動注入進來 private JDBCSettings jdbcSettings; @GetMapping("/v1/getJdbcProperties") public Object getJDBCProperties() { return jdbcSettings; } }
啟動項目訪問:
三、不足之處,后續補充。。。