1 Pom****文件html
1.1 spring-boot-starter-parentjava
表示當前pom文件從spring-boot-starter-parent繼承下來,在spring-boot-starter-parent中提供了不少默認配置,mysql
能夠簡化咱們的開發。 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
react
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> - 依賴管理spring-boot-dependencies <properties> <activemq.version>5.15.9</activemq.version> <antlr2.version>2.7.7</antlr2.version> <appengine-sdk.version>1.9.73</appengine-sdk.version> <artemis.version>2.6.4</artemis.version> ... </properties>web
這樣好比使用starter-web的時候就不須要指定版本號 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.4.RELEASE</version> </dependencyspring
使用本身的parent項目sql
這時候將依賴管理的問題放到dependencyManagement中。 官網說明文檔見:13.2.2 Using Spring Boot without the Parent POMmongodb
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.4.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>數據庫
1.2 打包管理api
使用mvn package打包的plugin。
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
1.3 Starters
官網見:13.5 Starters
Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa dependency in your project.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency>
2 XXXApplication
2.1 @SpringBootApplication 官網見:18. Using the @SpringBootApplication Annotation 等同於@EnableAutoConfiguration,@ComponentScan和@Configuration 2.2 SpringApplication.run 官網見:23. SpringApplication 3 配置文件 3.1 初步感覺 server.port=9090 3.2 yml文件 application.yml 3.3 給屬性注入值 實體類Person和IDCard public class Person { private String name; private int age; private Date birthday; private String[] hobbies; private IDCard idCard; ... }
public class IDCard { private int id; private String number; }
yml注入寫法
person: name: Jack age: 17 birthday: 1997/06/01 hobbies: [code,sing,share] idCard: id: 1 number: 111
Person類增長註解 @Component @ConfigurationProperties(prefix="person")
測試
@Autowired private Person person;
若是Person類上報錯,在Pom文件中加入以下依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId</dependency
4 處理動靜態資源 4.1 動態資源 官網見:90.2 Reload Templates without Restarting the Container templates resources目錄下有一個templates文件夾,能夠將動態資源放到其中 引入thymeleaf
<!--thymeleaf的jar包-->
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> templates下新建test.html文件 <html xmlns:th="http://www.thymeleaf.org"> <head> </head> <body> <span style="color:red; font-size:30pt" th:text="${str}"></span> </body> controller中return test @Controller @RequestMapping("/gupao") public class GupaoController { @RequestMapping("/hello") public String hello(Model model){ String str="hello spring boot"; //想要動態的顯示在網頁當中 model.addAttribute("str",str); //接下來的頁面是可以動態顯示傳過來的數據 return "test"; } } 4.2 靜態資源 static文件夾 在resources目錄下有一個static文件夾,能夠將靜態資源放到其中,瀏覽器能夠直接訪問。 靜態資源其餘存放文件夾 "classpath:/META-INF/resources/" "classpath:/resources/" "classpath:/static/" "classpath:/public/" WebMvcAutoConfiguration源碼分析 WebMvcAutoConfiguration--->WebMvcAutoConfigurationAdapter.addResourceHandlers(xxx)---> `this.resourceProperties.getStaticLocations()` `return this.staticLocations;` `private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;` `private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" };` 自定義靜態資源文件夾 觀察 @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) public class ResourceProperties { 配置application.properties spring.resources.static-locations=classpath:/gupao/ 5 整合MyBatis 5.1 需求 經過Spring Boot Web項目api接口的方式,整合MyBatis實現crud的操做。 5.2 建立Spring Boot Web項目 重溫一下web項目建立的過程。 5.3 引入項目中須要的starter依賴 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> 5.4 建立數據庫表 db_gupao_springboot--->t_user 5.5 建立domain/User對象 public class User { private int id; private String username; private String password; private String number; ... } 5.6 開發dao層 @Repository @Mapper public interface UserMapper { User find(String username); List<User> list(); int insert(User user); int delete(int id); int update(User user); } 5.7 開發service層 @Service public class UserService { @Autowired public UserMapper userMapper; public User findByUsername(String username){ return userMapper.find(username); } public List<User> listUser(){ return userMapper.list(); } public int insertUser(User user){ return userMapper.insert(user); } public int updateUser(User user){ return userMapper.update(user); } public int delete(int id){ return userMapper.delete(id); } } 5.8 開發controller層 @RestController @RequestMapping(value="/user",method = {RequestMethod.GET,RequestMethod.POST}) public class UserController { @Autowired private UserService userService; @RequestMapping("/listone") @ResponseBody public User listOne(String username){ return userService.findByUsername(username); } @RequestMapping("/listall") @ResponseBody public List<User> listAll(){ return userService.listUser(); } @RequestMapping(value="/add",method= RequestMethod.POST) @ResponseBody public String add(User user){ int result=userService.insertUser(user); if(result>=1) { return "添加成功"; }else{ return "添加失敗"; } } @RequestMapping(value="/update",method= RequestMethod.POST) @ResponseBody public String update(User user){ int result=userService.updateUser(user); if(result>=1) { return "修改爲功"; }else{ return "修改失敗"; } } @RequestMapping(value="/delete",method= RequestMethod.GET) @ResponseBody public String delete(int id){ int result=userService.delete(id); if(result>=1) { return "刪除成功"; }else{ return "刪除失敗"; } } } 5.9 resources目錄下建立mapper文件夾---UserMapper.xml <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD com.example.Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.csdn.springbootmybatis.dao.UserMapper"> <resultMap id="result" type="com.gupao.springbootmybatis.domain.User"> <result property="username" column="username"/> <result property="password" column="password"/> <result property="number" column="number"/> </resultMap> <select id="find" resultMap="result"> SELECT * FROM t_user where username=#{username} </select> <select id="list" resultMap="result"> SELECT * FROM t_user </select> <insert id="insert" parameterType="com.gupao.springbootmybatis.domain.User" keyProperty="id" useGeneratedKeys="true"> INSERT INTO t_user ( id,username,password,number ) VALUES ( #{id}, #{username, jdbcType=VARCHAR}, #{password, jdbcType=VARCHAR}, #{number} ) </insert> <delete id="delete" parameterType="int"> delete from t_user where id=#{id} </delete> <update id="update" parameterType="com.gupao.springbootmybatis.domain.User"> update t_user set user.username=#{username},user.password=#{password},user.number=# {number} where user.id=#{id} </update> </mapper> 5.10 application.properties文件配置 #數據源 spring: datasource: url: jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&characterEncoding=UTF- 8&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver #mybatis託管mapper文件 mybatis: mapper-locations: classpath:mapper/*.xml 5.11 啓動項目測試 查詢 http://localhost:8888/user/listone?username=Jack 所有查詢 http://localhost:8888/user/listall 增長 http://localhost:8888/user/add?id=3&username=AAA&password=111111&number=300 更新 http://localhost:8888/user/update?id=3&username=BBB 刪除 http://localhost:8888/user/delete?id=3 6 項目打包 jar包 mvn -Dmaven.test.skip -U clean install java -jar xxx.jar war包 <groupId>com.csdn</groupId> <artifactId>springboot-demo2</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> 7 Spring Boot in less than 10 minutes https://www.youtube.com/watch?v=lhkwLtDIMHI&feature=youtu.be BUILD ANYTHING WITH SPRING BOOT Spring Boot is the starting point for building all Spring-based applications. Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring. ![](https://oscimg.oschina.net/oscnet/4c5cf450bce8027f451d64d95524a4d4b0e.jpg) 7.1 IDEA建立工程 group:com.example artifact:bootiful dependencies:Reactive Web,Reactive MongoDB,Lombok,Actuator,Security 7.2 DATA DRIVE > Spring Data integrates seamlessly with SQL and NoSQL persistence stores. Spring Data supports reactive data access,too!
@Component class DataWriter implements ApplicationRunner { private final CustomerRepository customerRepository; DataWriter(CustomerRepository customerRepository) { this.customerRepository = customerRepository; } @Override public void run(ApplicationArguments args) throws Exception { Flux.just("Jack", "Rechal", "Richard", "Jobs") .flatMap(name -> customerRepository.save(new Customer(null, name))) .subscribe(System.out::println); } } interface CustomerRepository extends ReactiveMongoRepository<Customer, String> { } @Document @NoArgsConstructor @Data class Customer { private String id,name; public Customer(String id, String name) { this.id = id; this.name = name; } } 7.3 REST On the web,nobody knows you're a reactive microservice. @SpringBootApplication public class BootifulApplication { @Bean RouterFunction<ServerResponse> routes(CustomerRepository cr){ return RouterFunctions.route(GET("/customers"),serverRequest -> ok().body(cr.findAll(),Customer.class)); } public static void main(String[] args) { SpringApplication.run(BootifulApplication.class, args); } } 7.4 OBSERVABILITY How's your app's health?Who better to articulate that then the application itself? Spring Boot featurese strong opinions,loosely held. It's easy to change any of them with properties or pluggable implementations management.endpoint.health.show-details=always management.endpoints.web.exposure.exclude=* @Bean HealthIndicator healthIndicator(){ return () -> Health.status("I <3 Production").build(); } 訪問:curl http://localhost:8080/actuator/health | jq
7.5 SECURITY Effortlessly plugin authentication and authorization in a traditional or reactive application with Spring Security @Bean MapReactiveUserDetailsService users(){ return new MapReactiveUserDetailsService(User.withDefaultPasswordEncoder().username("user").password(" pw").roles("USER").build()); }
訪問:curl -vu user:pw http://localhost:8080/customers | jq
7.6 TO PRODUCTION Let's provision a MongoDB instance,configure our application's route and MongoDB binding,and then push our application to production with Cloud Foundry. 命令切換到bootiful根目錄下 cf services 定位到my-mongodb文件夾 複製對應文件,修改和觀察