微服務
微服務是一個新興的軟件架構,就是把一個大型的單個應用程序和服務拆分為數十個的支持微服務。一個微服務的策略可以讓工作變得更為簡便,它可擴展單個組件而不是整個的應用程序堆棧,從而滿足服務等級協議。
第一個SpringBoot程序
這里使用的開發軟件是IntelliJ Idea
,和Eclipse
差不太多,界面更炫酷,功能更強大;Android Studio
就是基於IntelliJ
開發的,我之前使用過Android Studio
,它倆界面幾乎一樣。
maven配置的中央倉庫阿里雲鏡像
setting.xml
<mirrors> <mirror> <id>alimaven</id> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> </mirrors>
使用IDEA
創建SpringBoot項目
刪除三個不必要的文件
項目結構為:
項目默認的 maven pom.xml
文件
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.newer</groupId> <artifactId>springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
運行SpirngbootdemoApplication
的main方法,就能開始運行
控制台輸出:
"C:\Program Files\Java\jdk1.8.0_91\bin\java" .... . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.4.2.RELEASE) 2016-12-16 14:56:52.083 INFO 15872 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2016-12-16 14:56:52.215 INFO 15872 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2016-12-16 14:56:52.255 INFO 15872 --- [ main] com.jxust.SpirngbootdemoApplication : Started SpirngbootdemoApplication in 7.795 seconds (JVM running for 9.177)
創建一個HelloController
,位於controller
包下
HelloController.java
@RestController public class HelloController { @RequestMapping("/hello") public String say(){ return "Hello SpringBoot!"; } }
@RestController Spring4 之后新加的注解,原來返回json需要@ResponseBody配合@Controller,現在一個頂倆
在瀏覽器中輸入http://localhost:8080/hello
就能輸出Hello SpringBoot!
這句話。
自定義屬性配置
用到的是application.properties
這個文件
配置端口號和訪問前綴
application.properties
server.port=8086 server.servlet.context-path=/springboot
除了使用.properties
格式的文件,還可以使用.yml
格式的配置文件(推薦),更加簡便 application.yml
把原來的application.properties
文件刪除
注意格式,空格不能少
獲取配置文件中的屬性值
我們也可以在配置文件中,配置數據,在 Controller 中獲取,比如: application.yml
HelloController 獲取配置文件中的值
HelloController.java
@RestController public class HelloController { @Value("${name}") private String name; @RequestMapping(value = "/hello" ,method = RequestMethod.GET) public String getName(){ return name; } }
返回的為name的值
配置文件中值配置方式的多樣化
配置文件的值可以是多個,也可以是組合,如:
application.yml
name: 小胖 age: 22
或者
application.yml
name: 小胖 age: 22 content: "name: ${name},age: ${age}"
或者
application.yml
server: port: 8081 context-path: /springboot person: name: 小胖 age: 22
前兩種配置獲取值的方式都是一樣的,但是對於這種方式,person 有相應的兩個屬性,需要這樣處理
PersonProperties.java
package com.newer.springboot.dao;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author:Mr.Tan
* @Create:2018-10-26-17-07
**/
@Component//(把普通pojo實例化到spring容器中,相當於配置文件中的<bean id="" class=""/>)
@ConfigurationProperties(prefix="person")
public class PersonProperties {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
@Component//(把普通pojo實例化到spring容器中,相當於配置文件中的<bean id="" class=""/>)
Alt+insert
快捷鍵提示生成Getter and Setter
pom.xml
需要加入下面的依賴,處理警告
<!--處理警告--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
HelloController.java
@RestController public class HelloController { @Autowired private PersonProperties personProperties; @RequestMapping(value = "/hello",method = RequestMethod.GET) public String say(){ return personProperties.getName()+personProperties.getAge(); } }
關於配置文件application.yml
的多套配置
類似 il8n 文件國際化的配置方式i18n_en_US.properties和i18n_zh_CN.properties 這樣能解決,需要頻繁修改配置的尷尬
由application.yml
配置文件決定使用那套配置文件。
application.yml
application-a.yml
application-b.yml
SpringBoot增刪改查實例
完整的項目結構
Controller的使用
@Controller 處理http請求 @RestController Spring4 之后新加的注解,原來返回json需要@ResponseBody配合@Controller @RequestMapping 配置url映射
對於 REST 風格的請求
對於 Controller 中的方法上的注解
@RequestMapping(value = "/hello",method = RequestMethod.GET) @RequestMapping(value = "/hello",method = RequestMethod.POST) @RequestMapping(value = "/hello",method = RequestMethod.DELETE) @RequestMapping(value = "/hello",method = RequestMethod.PUT)
SpringBoot 對上面的注解進行了簡化
@GetMapping(value = "/girls") @PostMapping(value = "/girls") @PutMapping(value = "/girls/{id}") @DeleteMapping(value = "/girls/{id}")
瀏覽器需要發送不同方式的請求,可以采用postman
spring-data-jpa
JPA
全稱Java Persistence API.JPA
通過JDK 5.0
注解或XML
描述對象-關系表的映射關系,並將運行期的實體對象持久化到數據庫中。
利用JPA創建MySQL數據庫
pom.xml
加入JPA
和MySQL
的依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
配置JPA
和數據庫
application.yml
spring: profiles: active: a datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/test username: root password: password jpa: hibernate: ddl-auto: update show-sql: true
格式很重要 需要自己手動去創建 db_person 數據庫
創建與數據表對應的實體類Person
Person.java
package com.newer.springboot.pojo; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author:Mr.Tan * @Create:2018-10-27-04-05 **/ @Entity public class Person { @Id @GeneratedValue private Integer id; private String name; private Integer age; //必須要有構造函數 public Person() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
運行項目后,查看數據庫,會自動創建表 person
接下來就可以進行person表的增刪改查了
創建控制器PersonController.java
首先創建一個接口PersonRepository
,位於dao
包下,PersonController
調用該接口繼承自JpaRepository
的方法,來實現和數據庫交互
這個PersonRepository接口的功能,與SSM框架中 dao 層接口功能有異曲同工之妙;在SSM框架中,Service層通過該接口,間接執行Mybatis數據庫映射文件(.xml)里的相應sql語句,執行數據庫增刪改查的操作。(Mapper自動實現DAO接口)
PersonRepository.java
import com.newer.springboot.pojo.Person; import org.springframework.data.jpa.repository.JpaRepository; /** * @author:Mr.Tan * @Create:2018-10-26-17-07 **/ public interface PersonProperties extends JpaRepository<Person, Integer> { }
PersonController.java
package com.newer.springboot.Controller; import com.newer.springboot.dao.PersonProperties; import com.newer.springboot.pojo.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @author:Mr.Tan * @Create:2018-10-27-04-09 **/ @RestController public class PersonController { @Autowired private PersonProperties personProperties; @GetMapping("/person") private List<Person> personList(){ return personProperties.findAll(); } }
在數據庫中添加兩條數據
啟動項目執行請求http://localhost:8086/springboot/person
其他增刪改查的方法
PersonController.java
package com.newer.springboot.Controller; import com.newer.springboot.dao.PersonProperties; import com.newer.springboot.pojo.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author:Mr.Tan * @Create:2018-10-27-04-09 **/ @RestController public class PersonController { @Autowired private PersonProperties personProperties; @GetMapping("/person") private List<Person> personList(){ return personProperties.findAll(); } /* 新增一個人員*/ @PostMapping(value = "/personadd") private Person add(@RequestParam ("name")String name,@RequestParam("age")Integer age){ Person person =new Person(); person.setName(name); person.setAge(age); return personProperties.save(person); } /** * 根據id查找一個人員 */ @GetMapping(value = "/person/{id}") public Person personFindOne(@PathVariable("id") Integer id) { return personProperties.findById(id).get(); } /** * 刪除一個員工 */ @DeleteMapping(value = "/person/{id}") public void deletep(@PathVariable("id") Integer id){ personProperties.deleteById(id); } /** * 更新一個員工 */ @PutMapping(value = "/per/{id}") public Person put(@PathVariable("id") Integer id, @RequestParam ("name") String name, @RequestParam ("age") Integer age){ Person person=new Person(); person.setName(name); person.setAge(age); return personProperties.save(person); } }
獲取所有人員
增加一個人員
根據id查找一個員工
刪除一個員工
更新一個員工
根據年齡查詢
在Personpository
增加一個方法findByAge(Integer age)
public interface PersonProperties extends JpaRepository<Person, Integer> { //通過年齡來查詢 public List<Person> findbyage( Integer age); }
在PersonController
中加入相應的查詢方法
/** * 根據年齡來查找 * @param age * @return */ @GetMapping(value = "/person/age/{age}") public List<Person> personListByAge(@PathVariable("age") Integer age){ return personProperties.findByage(age); }
事務管理
兩條 sql 語句同時在一個方法中執行,為了防止一個 sql 語句執行成功而另一個 sql 語句執行失敗,引入了事務管理,需要在方法上加 @Transactional
事務注解
PersonService.java
package com.newer.springboot.service; import com.newer.springboot.dao.PersonProperties; import com.newer.springboot.pojo.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; /** * @author:Mr.Tan * @Create:2018-10-27-23-04 **/ @Service public class PersonService { @Autowired private PersonProperties personProperties; /** * 事務管理測試 * 兩條數據同時成功,或者同時不成功 * 保證數據庫數據的完整性和一致性 */ @Transactional public void insertTwo(){ Person personA = new Person(); personA.setName("秋雅"); personA.setAge(19); personProperties.save(personA); System.out.print(1/0); Person personB = new Person(); personB.setName("夢特嬌"); personB.setAge(25); personProperties.save(personB); } }
在PersonController
中測試
... @Autowired private PersonService personService; ... /** * 事務測試 */ @PostMapping("/person/two") public void personTwo(){ personService.insertTwo(); }
重新運行項目,執行請求 post方式http://localhost:8081/springboot/person/two
數據庫並沒有添加第一條數據,說明存在事務管理