1.首先配置pom.xml里的依赖
org.springframework.bootspring-boot-configuration-processortrue
2.在:"项目所在文件夹springbootxxxsrcmainesourcesapplication.properties"路径下的application.properties文件配置参数,例如:
database.driverName=com.mysql.jdbc.Driverdatabase.url=jdbc:mysql://localhost:3306/my_mall?useUnicode=true&characterEncoding=utf-8&useSSL=falsedatabase.username=rootdatabase.password=root
3.创建一个新类DataBaseProperties
package com.springboot.chapter3Scan.propers;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;/** * 描述:使用属性配置 * * @author * @create 2019-03-16 9:35 /@Componentpublic class DataBaseProperties { @Value("${database.driverName}") private String driverName = null; @Value("${database.url}") private String url = null; private String userName = null; private String passWord = null; public void setDriverName(String driverName) { this.driverName = driverName; } public void setUrl(String url) { this.url = url; } @Value("${database.username}") public void setUserName(String userName) { this.userName = userName; } @Value("${database.password}") public void setPassWord(String passWord) { this.passWord = passWord; } public String getDriverName() { return driverName; } public String getUrl() { return url; } public String getUserName() { return userName; } public String getPassWord() { return passWord; }}
4.添加Controller类properController
package com.springboot.chapter3Scan.controller;import com.springboot.chapter3Scan.propers.DataBaseProperties;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;/** * 描述: * * @author * @create 2019-03-16 10:08 */@Controllerpublic class properController { @Autowired private DataBaseProperties dbp = null; @RequestMapping("/dbp") @ResponseBody public DataBaseProperties getDbp() { return dbp; } public void setDbp(DataBaseProperties dbp) { this.dbp = dbp; }}
5.使用主函数启动
package com.springboot.chapter3Scan.main;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import java.sql.SQLException;@SpringBootApplication(scanBasePackages = "com.springboot.chapter3Scan")//@ComponentScanpublic class Chapter3ScanApplication { public static void main(String[] args) throws SQLException { SpringApplication.run(Chapter3ScanApplication.class, args); }}
6.打开浏览器访问http://localhost:8080/dbp
即可访问返回的json数据
项目的路径如下: