一、項目結構介紹
如上圖所示,Spring Boot的基礎結構共三個文件:
src/main/java 程序開發以及主程序入口
src/main/resources 配置文件
src/test/java 測試程序
二、application.properties 配置文件
默認啟動項目的url配置,不需要加項目路徑默認為/ 可以自行修改。
端口默認8080 修改端口號為8888
項目名稱server.context-path
server.port=8888
server.context-path=/HelloWorld
helloWorld=spring boot
@Value("${helloWorld}")根據key-value直接注入helloWorld
@RestController
public class HelloWorldController {
@Value("${helloWorld}")
private String helloWorld;
@RequestMapping("/helloWorld")
public String say(){
return helloWorld;
}
}
@RestController的意思就是controller里面的方法都以json格式輸出,不用再寫什么jackjson配置的了!
啟動主程序,打開瀏覽器訪問http://localhost:8080/HelloWorld/helloWorld,就可以看到效果了。頁面輸出spring boot
三、@Value將外部配置文件的值動態注入到Bean
配置文件主要有兩類:
application.properties。application.properties在spring boot啟動時默認加載此文件
自定義屬性文件。自定義屬性文件通過@PropertySource加載。@PropertySource可以同時加載多個文件,也可以加載單個文件。如果相同第一個屬性文件和第二屬性文件存在相同key,則最后一個屬性文件里的key啟作用。加載文件的路徑也可以配置變量,如下文的${anotherfile.configinject},此值定義在第一個屬性文件config.properties
第一個屬性文件config.properties內容如下:
${anotherfile.configinject}作為第二個屬性文件加載路徑的變量值
book.name=bookName
anotherfile.configinject=placeholder
第二個屬性文件config_placeholder.properties內容如下:
book.name.placeholder=bookNamePlaceholder
下面通過@Value(“${app.name}”)語法將屬性文件的值注入bean屬性值
@Component
// 引入外部配置文件組:${app.configinject}的值來自config.properties。
// 如果相同
@PropertySource({"classpath:com/hry/spring/configinject/config.properties",
"classpath:com/hry/spring/configinject/config_${anotherfile.configinject}.properties"})
public class ConfigurationFileInject{
@Value("${app.name}")
private String appName; // 這里的值來自application.properties,spring boot啟動時默認加載此文件
@Value("${book.name}")
private String bookName; // 注入第一個配置外部文件屬性
@Value("${book.name.placeholder}")
private String bookNamePlaceholder; // 注入第二個配置外部文件屬性
@Autowired
private Environment env; // 注入環境變量對象,存儲注入的屬性值
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("bookName=").append(bookName).append("\r\n")
.append("bookNamePlaceholder=").append(bookNamePlaceholder).append("\r\n")
.append("appName=").append(appName).append("\r\n")
.append("env=").append(env).append("\r\n")
// 從eniroment中獲取屬性值
.append("env=").append(env.getProperty("book.name.placeholder")).append("\r\n");
return sb.toString();
}
}
Application.java同上文
@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
public class ConfiginjectApplicationTest {
@Autowired
private ConfigurationFileInject configurationFileInject;
@Test
public void configurationFileInject(){
System.out.println(configurationFileInject.toString());
}
}
測試結果
bookName=bookName
bookNamePlaceholder=bookNamePlaceholder
appName=appName
env=StandardEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[Inlined Test Properties,systemProperties,systemEnvironment,random,applicationConfig: [classpath:/application.properties],class path resource [com/hry/spring/configinject/config_placeholder.properties],class path resource [com/hry/spring/configinject/config.properties]]}
env=bookNamePlaceholder
四、application.properties配置數據庫連接
有前綴的屬性注入
請求url
mysql.jdbcName=com.mysql.jdbc.Driver
mysql.dbUrl=jdbc:mysql://localhost:3306/db_boot
mysql.userName=root
mysql.password=123456
@Component 讓spring加載
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Mysql屬性配置文件
* @author Administrator
*
*/
@RestController
public class MysqlProperties {
@Value("${mysql.jdbcName}")
private String jdbcName;
@Value("${mysql.dbUrl}")
private String dbUrl;
@Value("${mysql.userName}")
private String userName;
@Value("${mysql.password}")
private String password;
public String getJdbcName() {
return jdbcName;
}
public void setJdbcName(String jdbcName) {
this.jdbcName = jdbcName;
}
public String getDbUrl() {
return dbUrl;
}
public void setDbUrl(String dbUrl) {
this.dbUrl = dbUrl;
}
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;
}
}
@ConfigurationProperties(prefix="mysql") 就是application配置文件的前綴mysql
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Mysql屬性配置文件
* @author Administrator
*
*/
@Component
@ConfigurationProperties(prefix="mysql")
public class MysqlProperties {
private String jdbcName;
private String dbUrl;
private String userName;
private String password;
public String getJdbcName() {
return jdbcName;
}
public void setJdbcName(String jdbcName) {
this.jdbcName = jdbcName;
}
public String getDbUrl() {
return dbUrl;
}
public void setDbUrl(String dbUrl) {
this.dbUrl = dbUrl;
}
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;
}
}
@Component已經變為spring管理的bean了@Resource 直接引入
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@Resource
private MysqlProperties mysqlProperties;
@RequestMapping("/showJdbc")
public String showJdbc(){
return "mysql.jdbcName:"+mysqlProperties.getJdbcName()+"<br/>"
+"mysql.dbUrl:"+mysqlProperties.getDbUrl()+"<br/>"
+"mysql.userName:"+mysqlProperties.getUserName()+"<br/>"
+"mysql.password:"+mysqlProperties.getPassword()+"<br/>";
}
}
五、spring處理http請求
@Controller 處理http請求的注解,請求后台轉發頁面
@RequestMapping 映射路徑
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/freemarker")
public class HelloWorldFreemarkerController {
@RequestMapping("/say")
public ModelAndView say(){
ModelAndView mav=new ModelAndView();
mav.addObject("message", "springboot!");
mav.setViewName("helloWorld");
return mav;
}
}
helloWorld的模板文件
helloWorld.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
show: ${message}
</body>
</html>
@PathVariable獲取url參數
@RequestParam 獲取get或post參數或者是form和url參數
rest風格的資源url請求
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://www.java1234.com/jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript">
function show(){
$.post("ajax/hello",{},function(result){
alert(result);
});
}
</script>
</head>
<body>
<button onclick="show()">你好</button>
<a href="/HelloWorld/blog/21">天天</a>
<a href="/HelloWorld/blog/query?q=123456">搜索</a>
</body>
</html>
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/ajax")
public class HelloWorldAjaxController {
@RequestMapping("/hello")
public String say(){
return "{'message1':'SpringBoot你好','message2','Spring你好2'}";
}
}
@PathVariable獲取url參數
<a href="/HelloWorld/blog/21"></a>
<a href="/HelloWorld/blog/query?q=123456">搜索</a>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/blog")
public class BlogController {
@RequestMapping("/{id}")
public ModelAndView show(@PathVariable("id") Integer id){
ModelAndView mav=new ModelAndView();
mav.addObject("id", id);
mav.setViewName("blog");
return mav;
}
@RequestMapping("/query")
public ModelAndView query(@RequestParam(value="q",required=false)String q){
ModelAndView mav=new ModelAndView();
mav.addObject("q", q);
mav.setViewName("query");
return mav;
}
}
blog.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
id:${id}
</body>
</html>
---------------------
作者:wespten
來源:CSDN
原文:https://blog.csdn.net/qq_35029061/article/details/81926967
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!