Spring boot入门篇

  1. Spring
    Boot是由Pivotal团队提供的全新框架,其安排指标是用来简化新Spring应用的上马搭建以及支付进度。该框架使用了一定的法子来张开配备,进而使开拓职员不再必要定义样板化的安插。通过这种情势,Boot致力于在如日方升的高速利用开辟领域(rapid
       application  development)成为官员。
     能够 Maven | Gradle | Ant |
    Starters构建项目,参谋:http://start.spring.io/ 能够挑选Maven或Gradle生成Demo,Spring
    boot微服务架构重组Docker容器运行。
      软件版本运转要求请参照他事他说加以考察官方网站: Spring boot官网  
    本实例软件版本:JDK1.7 + Spring boot 1.3.5 + Spring 4.2.6 

0005 SpringBoot HelloWord Demo项目

  常用的starter以及用处能够列举如下:

请参谋前几篇内容,安装好Java及Maven版本

(1)spring-boot-starter: 那是主导Spring Boot
starter,提供了绝大许多基础功效,别的starter都凭仗于它,因而并无需显式定义它。

1.行使Eclipse创设三个Maven项目

(2)spring-boot-starter-actuator:主要提供监控、管理和审核应用程序的法力。

并修改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>

(3)spring-boot-starter-jdbc:该starter提供对JDBC操作的支撑,包罗三番两次数据库、操作数据库,以及管理数据库连接等等。

<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.BUILD-SNAPSHOT</version>
</parent>

<!-- Additional lines to be added here... -->

<!-- (you don't need this if you are using a .RELEASE version) -->
<repositories>
    <repository>
        <id>spring-snapshots</id>
        <url>http://repo.spring.io/snapshot</url>
        <snapshots><enabled>true</enabled></snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <url>http://repo.spring.io/milestone</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-snapshots</id>
        <url>http://repo.spring.io/snapshot</url>
    </pluginRepository>
    <pluginRepository>
        <id>spring-milestones</id>
        <url>http://repo.spring.io/milestone</url>
    </pluginRepository>
</pluginRepositories>

(4)spring-boot-starter-data-jpa:JPA starter提供使用Java Persistence
API(举例Hibernate等)的注重库。

</project>

(5)spring-boot-starter-data-*:提供对MongoDB、Data-Rest或者Solr的支持。

2.新扩大web项目有关的Maven注重包

(6)spring-boot-starter-security:提供具备Spring-security的重视库。

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

(7)spring-boot-starter-test:那一个starter包涵了spring-test依赖以及其它测量试验框架,举例JUnit和Mockito等等。

</dependency>
</dependencies>

(8)spring-boot-starter-web:该starter包含web应用程序的重视库。

3.制造二个Controller代码

2.Maven营造项目pom代码

import org.springframework.boot.;
import org.springframework.boot.autoconfigure.
;
import org.springframework.stereotype.;
import org.springframework.web.bind.annotation.
;

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3     <modelVersion>4.0.0</modelVersion>
  4 
  5     <groupId>ygnet</groupId>
  6     <artifactId>boot</artifactId>
  7     <version>0.0.1-SNAPSHOT</version>
  8     <packaging>jar</packaging>
  9 
 10     <name>Springboot</name>
 11     <url>http://maven.apache.org</url>
 12     
 13     <properties>
 14         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 15         <java.version>1.7</java.version>
 16     </properties>
 17     
 18     <!-- Spring Boot 启动父依赖 -->
 19     <parent>
 20         <groupId>org.springframework.boot</groupId>
 21         <artifactId>spring-boot-starter-parent</artifactId>
 22         <version>1.3.5.RELEASE</version>
 23         <relativePath />
 24     </parent>
 25     <dependencies>
 26         <dependency>
 27             <groupId>junit</groupId>
 28             <artifactId>junit</artifactId>
 29             <version>4.12</version>
 30             <scope>test</scope>
 31         </dependency>
 32         <dependency>
 33           <groupId>org.springframework</groupId>
 34           <artifactId>spring-test</artifactId>
 35           <version>4.2.6.RELEASE</version>
 36         </dependency>
 37             
 38         <!-- Spring Boot web依赖 -->
 39         <dependency>
 40             <groupId>org.springframework.boot</groupId>
 41             <artifactId>spring-boot-starter-web</artifactId>
 42         </dependency>
 43         <dependency>
 44             <groupId>org.springframework.boot</groupId>
 45             <artifactId>spring-boot-starter</artifactId>
 46         </dependency>    
 47         <!--dependency>
 48             <groupId>org.springframework.boot</groupId>
 49             <artifactId>spring-boot-starter-test</artifactId>
 50             <scope>test</scope>
 51         </dependency-->
 52         <dependency>
 53             <groupId>org.springframework.boot</groupId>
 54             <artifactId>spring-boot-starter-jdbc</artifactId>
 55         </dependency>
 56         <dependency>
 57             <groupId>org.postgresql</groupId>
 58             <artifactId>postgresql</artifactId><scope>runtime</scope>
 59         </dependency>
 60         <dependency>
 61             <groupId>org.springframework.boot</groupId>
 62             <artifactId>spring-boot-starter-actuator</artifactId>
 63         </dependency>
 64     </dependencies>
 65     <build>
 66         <pluginManagement>  
 67             <plugins>  
 68               <plugin>  
 69                 <groupId>org.eclipse.m2e</groupId>  
 70                 <artifactId>lifecycle-mapping</artifactId>  
 71                 <version>1.0.0</version>  
 72                 <configuration>  
 73                   <lifecycleMappingMetadata>  
 74                     <pluginExecutions>  
 75                       <pluginExecution>  
 76                         <pluginExecutionFilter>  
 77                           <groupId>org.apache.maven.plugins</groupId>  
 78                           <artifactId>maven-dependency-plugin</artifactId>  
 79                           <versionRange>[2.0,)</versionRange>  
 80                           <goals>  
 81                             <goal>copy-dependencies</goal>  
 82                           </goals>  
 83                         </pluginExecutionFilter>  
 84                         <action>  
 85                           <ignore />  
 86                         </action>  
 87                       </pluginExecution>  
 88                     </pluginExecutions>  
 89                   </lifecycleMappingMetadata>  
 90                 </configuration>  
 91               </plugin>  
 92             </plugins>  
 93         </pluginManagement>
 94         <plugins>
 95             <!-- 打Jar包(META-INF) -->
 96             <plugin>
 97                 <groupId>org.apache.maven.plugins</groupId>  
 98                 <artifactId>maven-jar-plugin</artifactId>  
 99                 <configuration>  
100                     <archive>  
101                         <manifest>  
102                            <addClasspath>true</addClasspath>  
103                            <classpathPrefix>lib/</classpathPrefix>  
104                            <mainClass>yg.boot.App</mainClass>  
105                         </manifest>  
106                     </archive>  
107                 </configuration>  
108             </plugin>
109             <!-- 项目资源文件 -->
110             <plugin>  
111                 <groupId>org.apache.maven.plugins</groupId>  
112                 <artifactId>maven-resources-plugin</artifactId>  
113                 <version>2.5</version>  
114                 <executions>  
115                     <execution>  
116                         <phase>compile</phase>  
117                     </execution>  
118                 </executions>  
119                 <configuration>  
120                     <encoding>${project.build.sourceEncoding}</encoding>  
121                 </configuration>  
122             </plugin>
123             <!-- 是否启动测试 -->
124             <plugin>
125                 <groupId>org.apache.maven.plugins</groupId>  
126                 <artifactId>maven-surefire-plugin</artifactId>
127                 <version>2.17</version> 
128                 <configuration>
129                   <skipTests>true</skipTests>  
130                 </configuration>
131             </plugin>
132             <!-- 复制依赖包到项目lib文件夹下 -->
133             <plugin>  
134                 <groupId>org.apache.maven.plugins</groupId>  
135                 <artifactId>maven-dependency-plugin</artifactId>  
136                 <version>2.8</version>  
137                 <executions>  
138                     <execution>  
139                         <phase>package</phase>  
140                         <goals>  
141                             <goal>copy-dependencies</goal>  
142                         </goals>  
143                     </execution>  
144                 </executions>
145                 <configuration>
146                     <outputDirectory>${project.basedir}/lib</outputDirectory>
147                     <includeScope>compile</includeScope>  
148                 </configuration>  
149             </plugin>
150             <!-- Spring boot 打包 -->
151             <plugin>
152                 <groupId>org.springframework.boot</groupId>
153                 <artifactId>spring-boot-maven-plugin</artifactId>
154             </plugin>
155         </plugins>
156     </build>
157 </project>

RestController与RequestMapping
皆以SpringMVC中的证明配置,要是不打听,能够去参谋SpringMVC的法定指南文书档案。

3.Controller

//配置RestController配置
//请注意Controller 与RestController 的区别
@RestController
@EnableAutoConfiguration
//配置后,Spring会基于POM的借助配置音讯去适合合适的重视性关系。
//比方这一次案例,pom配置了web正视,Spring会去适配web相关的布局音信
public class Example {

Spring
Boot框架提供的建制便于程序员完成标准的RESTful接口,编写Controller代码,首先大家要在pom文件中加上对应的starter,即spring-boot-starter-web,对应的xml代码示例为:
<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@RestController评释是@Controller和@ResponseBody的合集,表示那是个调节器bean,况兼是将函数的重返值直接填入HTTP响应体中,是REST风格的调控器。
@RequestMapping(“/test”)表示该调节器管理全体“/test”的UEvoqueL央求,具体由特别函数管理,要基于HTTP的措施来分别:GET表示查询、POST表示提交、PUT表示更新、DELETE代表删除。
Restful设计指南请参见:RESTFul Controller的剧中人物,大家能够看到,笔者这里将多数事情代码混淆在Controller的代码中。实际上,依照程序猿必知在此之前端演进史一文所述Controller层应该做的事是:
管理央浼的参数 渲染和重定向 选用Model和Service处理Session和Cookies,作者大约承认这么些思想,最多再增加OAuth验证(利用拦截器完毕就可以)。而实在的作业逻辑应该单独分处一层来拍卖,即常见的service层;

@RequestMapping("/")
String home() {
    return "Hello World!";
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(Example.class, args);//启动入口
}

 java代码:

}

 1 package yg.boot.action;
 2 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 3 import org.springframework.web.bind.annotation.RequestMapping;
 4 import org.springframework.web.bind.annotation.RestController;
 5 @RestController
 6 @EnableAutoConfiguration
 7 @RequestMapping("/test")
 8 public class AppController {    
 9     @RequestMapping("/sayhello")
10     public String sayHello(){
11         return "Hello World!";
12     }
13 }

4.启动bot项目
在Eclipse中执行 run java Application

4.Spring Boot启动  

5.在浏览器访谈
http://localhost:8080

 
@SpringBootApplication是以此注明是该应用程序入口的标识,然后有熟习的main函数,通过SpringApplication.run(xxxApplication.class,
args)来运行Spring Boot应用。张开SpringBootApplication注脚  
能够开掘,它是由其余多少个类组合而成的:@Configuration

假若一切平常能够在浏览器看到 Hello World!

(等同于
spring中的xml配置文件,使用Java文件做布置能够检查项目安全)、@EnableAutoConfiguration(自动配置)、@ComponentScan(组件扫描,我们十一分熟稔的,能够活动开掘和装配一些Bean)

6.营造可试行jar包
营造可推行jar包须求在pom中增多一下布置
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

 
 pom文件里能够看看,org.postgresql那些库起作用的界定是runtime,也正是说,当应用程序运营时,要是Spring
Boot在classpath下检测到org.postgresql的留存,会自行配置postgresql数据库连接。

7.执行Build操作
mvn package
[INFO] Scanning for projects…
[INFO]

Application.properties代码:

[INFO]

[INFO] Building myproject 0.0.1-SNAPSHOT

 1 # DataSource settings
 2 spring.datasource.url=jdbc:postgresql://localhost:5432/jcbk
 3 spring.datasource.username=jcbk
 4 spring.datasource.password=123456
 5 spring.datasource.driver-class-name=org.postgresql.Driver
 6 
 7 # Tomcat Server settings (ServerProperties)
 8 server.port= 9080
 9 server.address= 127.0.0.1
10 server.sessionTimeout= 30
11 server.contextPath= /
12 
13 # Tomcat specifics
14 tomcat.accessLogEnabled= false
15 tomcat.protocolHeader= x-forwarded-proto
16 tomcat.remoteIpHeader= x-forwarded-for
17 tomcat.basedir=
18 tomcat.backgroundProcessorDelay=30 \# secs

[INFO]

[INFO] …. ..
[INFO] — maven-jar-plugin:2.4:jar (default-jar) @ myproject —
[INFO] Building jar:
/Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] —
spring-boot-maven-plugin:2.0.0.BUILD-SNAPSHOT:repackage
(default) @ myproject —

java代码:

[INFO]

[INFO] BUILD SUCCESS

 1 package yg.boot;
 2 import org.springframework.boot.SpringApplication;
 3 import org.springframework.boot.autoconfigure.SpringBootApplication;
 4 /**
 5  * Hello world!
 6  */
 7 @SpringBootApplication
 8 public class App {    
 9     public static void main(String[] args ){
10         SpringApplication.run(App.class,args);
11     }
12 }

[INFO]

8.通过jar包运转服务

java -jar target/myproject-0.0.1-SNAPSHOT.jar

素来运转App后,结果如下图所示。运营后会见http://localhost:9080/test/sayhello,
输出 Hello World!,如下所示:

图片 1

5.档案的次序打包

类型打包使用maven-jar-plugin插件就能够,生成boot-0.0.1-SNAPSHOT.jar。spring-boot-maven-plugin插件将boot-0.0.1-SNAPSHOT.jar重命名称叫boot-0.0.1-SNAPSHOT.jar.original,然后生成新boot-0.0.1-SNAPSHOT.jar包,目录结构为:
+—yg
          boot
+—org
          springframework
              boot
                 loader
+—-lib
+—-META-INF
+—-application.properties

Meta-inf代码:

 1 Manifest-Version: 1.0
 2 Implementation-Vendor: Pivotal Software, Inc.
 3 Implementation-Title: Springboot
 4 Implementation-Version: 0.0.1-SNAPSHOT
 5 Implementation-Vendor-Id: ygnet
 6 Built-By: oy
 7 Build-Jdk: 1.7.0_45
 8 Class-Path: lib/spring-test-4.2.6.RELEASE.jar lib/spring-core-4.2.6.RE
 9  LEASE.jar lib/spring-boot-starter-web-1.3.5.RELEASE.jar lib/spring-bo
10  ot-starter-tomcat-1.3.5.RELEASE.jar lib/tomcat-embed-core-8.0.33.jar 
11  lib/tomcat-embed-el-8.0.33.jar lib/tomcat-embed-logging-juli-8.0.33.j
12  ar lib/tomcat-embed-websocket-8.0.33.jar lib/spring-boot-starter-vali
13  dation-1.3.5.RELEASE.jar lib/hibernate-validator-5.2.4.Final.jar lib/
14  validation-api-1.1.0.Final.jar lib/jboss-logging-3.3.0.Final.jar lib/
15  classmate-1.1.0.jar lib/jackson-databind-2.6.6.jar lib/jackson-annota
16  tions-2.6.6.jar lib/jackson-core-2.6.6.jar lib/spring-web-4.2.6.RELEA
17  SE.jar lib/spring-aop-4.2.6.RELEASE.jar lib/aopalliance-1.0.jar lib/s
18  pring-beans-4.2.6.RELEASE.jar lib/spring-context-4.2.6.RELEASE.jar li
19  b/spring-webmvc-4.2.6.RELEASE.jar lib/spring-expression-4.2.6.RELEASE
20  .jar lib/spring-boot-starter-1.3.5.RELEASE.jar lib/spring-boot-1.3.5.
21  RELEASE.jar lib/spring-boot-autoconfigure-1.3.5.RELEASE.jar lib/sprin
22  g-boot-starter-logging-1.3.5.RELEASE.jar lib/logback-classic-1.1.7.ja
23  r lib/logback-core-1.1.7.jar lib/slf4j-api-1.7.21.jar lib/jcl-over-sl
24  f4j-1.7.21.jar lib/jul-to-slf4j-1.7.21.jar lib/log4j-over-slf4j-1.7.2
25  1.jar lib/snakeyaml-1.16.jar lib/spring-boot-starter-jdbc-1.3.5.RELEA
26  SE.jar lib/tomcat-jdbc-8.0.33.jar lib/tomcat-juli-8.0.33.jar lib/spri
27  ng-jdbc-4.2.6.RELEASE.jar lib/spring-tx-4.2.6.RELEASE.jar lib/postgre
28  sql-9.4.1208.jre7.jar lib/spring-boot-starter-actuator-1.3.5.RELEASE.
29  jar lib/spring-boot-actuator-1.3.5.RELEASE.jar
30 Start-Class: yg.boot.App
31 Created-By: Apache Maven 3.0.4
32 Spring-Boot-Version: 1.3.5.RELEASE
33 Main-Class: org.springframework.boot.loader.JarLauncher
34 Archiver-Version: Plexus Archiver

 

 Start-Class为Spring boot运行类,Main-Class为main方法入口。

                                      END