天天看點

Spring Boot 快速入門(一)

簡介 

相信很多人都接觸spring架構很長時間了,每次搭建spring架構的時候都需要配置好多的jar、xml,做很多繁瑣重複的配置,稍微不留神就會出現各種各樣的問題,每次調試真的是香菇、藍瘦啊。

spring boot的出現幫助我們徹底解決了這些jar的依賴,隻需要很少的配置就可以完成我們的開發工作,我們可以把自己的應用打包成jar,使用java -jar來運作spring web應用,spring boot內建了很多的web容器,後面都會慢慢講到這些,今天我們就開始使用spring boot完成一個最簡單的web應用。

使用maven建構項目

spring官網提供了了一個非常友善的位址來幫助我們建立spring boot項目,

http://start.spring.io/

,輸入相關參數點選

Generate Project 即可下載下傳自動生成的壓縮包。

該項目采用maven建構,加壓後直接使用自己的IDE導入maven工程即可

1,打開pom檔案就可以看到新的項目比傳統的spring mvc項目的pom檔案接口清晰了很多

  

1         <parent>
2         <groupId>org.springframework.boot</groupId>
3         <artifactId>spring-boot-starter-parent</artifactId>
4         <version>1.4.1.RELEASE</version>
5     </parent>      

第一個地方是多了上面的代碼,這個spring boot會自動幫我門引入一些約定的配置,檢視源碼得知

Spring Boot 快速入門(一)
Spring Boot 快速入門(一)
1 <?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">
  2     <modelVersion>4.0.0</modelVersion>
  3     <parent>
  4         <groupId>org.springframework.boot</groupId>
  5         <artifactId>spring-boot-dependencies</artifactId>
  6         <version>1.4.1.RELEASE</version>
  7         <relativePath>../../spring-boot-dependencies</relativePath>
  8     </parent>
  9     <artifactId>spring-boot-starter-parent</artifactId>
 10     <packaging>pom</packaging>
 11     <name>Spring Boot Starter Parent</name>
 12     <description>Parent pom providing dependency and plugin management for applications
 13         built with Maven</description>
 14     <url>http://projects.spring.io/spring-boot/</url>
 15     <organization>
 16         <name>Pivotal Software, Inc.</name>
 17         <url>http://www.spring.io</url>
 18     </organization>
 19     <properties>
 20         <java.version>1.6</java.version>
 21         <resource.delimiter>@</resource.delimiter> <!-- delimiter that doesn't clash with Spring ${} placeholders -->
 22         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 23         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 24         <maven.compiler.source>${java.version}</maven.compiler.source>
 25         <maven.compiler.target>${java.version}</maven.compiler.target>
 26     </properties>
 27     <dependencyManagement>
 28         <dependencies>
 29             <dependency>
 30                 <groupId>org.springframework</groupId>
 31                 <artifactId>spring-core</artifactId>
 32                 <version>${spring.version}</version>
 33                 <exclusions>
 34                     <exclusion>
 35                         <groupId>commons-logging</groupId>
 36                         <artifactId>commons-logging</artifactId>
 37                     </exclusion>
 38                 </exclusions>
 39             </dependency>
 40         </dependencies>
 41     </dependencyManagement>
 42     <build>
 43         <!-- Turn on filtering by default for application properties -->
 44         <resources>
 45             <resource>
 46                 <directory>${basedir}/src/main/resources</directory>
 47                 <filtering>true</filtering>
 48                 <includes>
 49                     <include>**/application*.yml</include>
 50                     <include>**/application*.properties</include>
 51                 </includes>
 52             </resource>
 53             <resource>
 54                 <directory>${basedir}/src/main/resources</directory>
 55                 <excludes>
 56                     <exclude>**/application*.yml</exclude>
 57                     <exclude>**/application*.properties</exclude>
 58                 </excludes>
 59             </resource>
 60         </resources>
 61         <pluginManagement>
 62             <plugins>
 63                 <!-- Apply more sensible defaults for user projects -->
 64                 <plugin>
 65                     <groupId>org.apache.maven.plugins</groupId>
 66                     <artifactId>maven-failsafe-plugin</artifactId>
 67                     <executions>
 68                         <execution>
 69                             <goals>
 70                                 <goal>integration-test</goal>
 71                                 <goal>verify</goal>
 72                             </goals>
 73                         </execution>
 74                     </executions>
 75                 </plugin>
 76                 <plugin>
 77                     <groupId>org.apache.maven.plugins</groupId>
 78                     <artifactId>maven-jar-plugin</artifactId>
 79                     <configuration>
 80                         <archive>
 81                             <manifest>
 82                                 <mainClass>${start-class}</mainClass>
 83                                 <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
 84                             </manifest>
 85                         </archive>
 86                     </configuration>
 87                 </plugin>
 88                 <plugin>
 89                     <groupId>org.apache.maven.plugins</groupId>
 90                     <artifactId>maven-surefire-plugin</artifactId>
 91                     <configuration>
 92                         <includes>
 93                             <include>**/*Tests.java</include>
 94                             <include>**/*Test.java</include>
 95                         </includes>
 96                         <excludes>
 97                             <exclude>**/Abstract*.java</exclude>
 98                         </excludes>
 99                     </configuration>
100                 </plugin>
101                 <plugin>
102                     <groupId>org.apache.maven.plugins</groupId>
103                     <artifactId>maven-war-plugin</artifactId>
104                     <configuration>
105                         <failOnMissingWebXml>false</failOnMissingWebXml>
106                         <archive>
107                             <manifest>
108                                 <mainClass>${start-class}</mainClass>
109                                 <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
110                             </manifest>
111                         </archive>
112                     </configuration>
113                 </plugin>
114                 <plugin>
115                     <groupId>org.codehaus.mojo</groupId>
116                     <artifactId>exec-maven-plugin</artifactId>
117                     <configuration>
118                         <mainClass>${start-class}</mainClass>
119                     </configuration>
120                 </plugin>
121                 <plugin>
122                     <groupId>org.apache.maven.plugins</groupId>
123                     <artifactId>maven-resources-plugin</artifactId>
124                     <version>2.6</version>
125                     <configuration>
126                         <delimiters>
127                             <delimiter>${resource.delimiter}</delimiter>
128                         </delimiters>
129                         <useDefaultDelimiters>false</useDefaultDelimiters>
130                     </configuration>
131                 </plugin>
132                 <plugin>
133                     <groupId>pl.project13.maven</groupId>
134                     <artifactId>git-commit-id-plugin</artifactId>
135                     <version>2.1.11</version>
136                     <executions>
137                         <execution>
138                             <goals>
139                                 <goal>revision</goal>
140                             </goals>
141                         </execution>
142                     </executions>
143                     <configuration>
144                         <verbose>true</verbose>
145                         <dateFormat>yyyy-MM-dd'T'HH:mm:ssZ</dateFormat>
146                         <generateGitPropertiesFile>true</generateGitPropertiesFile>
147                         <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename>
148                     </configuration>
149                 </plugin>
150                 <!-- Support our own plugin -->
151                 <plugin>
152                     <groupId>org.springframework.boot</groupId>
153                     <artifactId>spring-boot-maven-plugin</artifactId>
154                     <executions>
155                         <execution>
156                             <goals>
157                                 <goal>repackage</goal>
158                             </goals>
159                         </execution>
160                     </executions>
161                     <configuration>
162                         <mainClass>${start-class}</mainClass>
163                     </configuration>
164                 </plugin>
165                 <!-- Support shade packaging (if the user does not want to use our plugin) -->
166                 <plugin>
167                     <groupId>org.apache.maven.plugins</groupId>
168                     <artifactId>maven-shade-plugin</artifactId>
169                     <dependencies>
170                         <dependency>
171                             <groupId>org.springframework.boot</groupId>
172                             <artifactId>spring-boot-maven-plugin</artifactId>
173                             <version>1.4.1.RELEASE</version>
174                         </dependency>
175                     </dependencies>
176                     <configuration>
177                         <keepDependenciesWithProvidedScope>true</keepDependenciesWithProvidedScope>
178                         <createDependencyReducedPom>true</createDependencyReducedPom>
179                         <filters>
180                             <filter>
181                                 <artifact>*:*</artifact>
182                                 <excludes>
183                                     <exclude>META-INF/*.SF</exclude>
184                                     <exclude>META-INF/*.DSA</exclude>
185                                     <exclude>META-INF/*.RSA</exclude>
186                                 </excludes>
187                             </filter>
188                         </filters>
189                     </configuration>
190                     <executions>
191                         <execution>
192                             <phase>package</phase>
193                             <goals>
194                                 <goal>shade</goal>
195                             </goals>
196                             <configuration>
197                                 <transformers>
198                                     <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
199                                         <resource>META-INF/spring.handlers</resource>
200                                     </transformer>
201                                     <transformer implementation="org.springframework.boot.maven.PropertiesMergingResourceTransformer">
202                                         <resource>META-INF/spring.factories</resource>
203                                     </transformer>
204                                     <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
205                                         <resource>META-INF/spring.schemas</resource>
206                                     </transformer>
207                                     <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
208                                     <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
209                                         <mainClass>${start-class}</mainClass>
210                                     </transformer>
211                                 </transformers>
212                             </configuration>
213                         </execution>
214                     </executions>
215                 </plugin>
216             </plugins>
217         </pluginManagement>
218     </build>
219 </project>      

View Code

   spring boot預設幫我引入的jdk版本是1.6,如果需要改動,則在自己pom檔案中直接重寫<java.version>1.6</java.version>即可。

   還可以看到它已經幫我們引入了spring-core和commons-logging包

   繼續往下看可以發現一些屬性檔案他也幫我定義好了規則,不需要我們自己在xml中定義了,已經一些maven插件的定義這裡就不一一說明 ,具體插件是做什麼用的,各位可以看下maven的相關知識。

第二個改變的地方是

1   <dependency>
 2     <groupId>org.springframework.boot</groupId>
 3     <artifactId>spring-boot-starter</artifactId>
 4 </dependency>
 5 
 6 <dependency>
 7     <groupId>org.springframework.boot</groupId>
 8     <artifactId>spring-boot-starter-test</artifactId>
 9     <scope>test</scope>
10 </dependency>
11 
12 <dependency>
13     <groupId>org.springframework.boot</groupId>
14     <artifactId>spring-boot-starter-web</artifactId>
15 </dependency>        
spring-boot-starter:核心子產品,包括自動配置支援、日志      
spring-boot-starter-test :測試子產品,包括JUnit、Hamcrest、Mockito      
spring-boot-starter-web  :開發web項目依賴

代碼編寫

說了這麼多的配置,來讓我們建立第一個class吧      
@Controller
@EnableAutoConfiguration
@RequestMapping("/ctr")
public class SampleController
{
    @RequestMapping("/getStr")
    @ResponseBody
    String home(){
        return "Hello World";
    }

    @RequestMapping("/info")
    @ResponseBody
    public Map<String,String> getInfo(){
        Map<String, String> map = new HashMap<>();
        map.put("name", "jack");
        return map;
    }

    
    public static void main(String[] args)
    {
        SpringApplication.run(SampleController.class,args);
    }
}      

到此為止,我們的第一個spring 的web項目就結束了,直接運作main方法,浏覽器中輸入:http://127.0.0.1:8080/ctr/info 可以看到運作結果  {"name": "jack"}

怎麼樣,是不是很神奇,沒有啟動任何的web容器,隻需要執行main方法就可以運作我們的web項目了,而且配置就這麼簡單任性。

開開心心編碼,快快樂樂生活。