2分鍾在eclipse下使用SpringBoot搭建Spring MVC的WEB項目


轉自:http://www.cnblogs.com/chry/p/5876752.html

 

1. 首先用eclipse創建一個maven工程, 普通maven工程即可

2. 修改pom如下:

復制代碼
<?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.chry</groupId>
    <artifactId>studySpringBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>1.7</java.version>
    </properties>
    
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>

    <!-- Add typical dependencies for a web application -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>    
    </dependencies>

    <!-- Package as an executable jar -->
    <build>
        <finalName>studySpringBoot</finalName>
    </build>
</project>
復制代碼

3. 接着創建一個Java Class

復制代碼
 1 package com.chry.study;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.ResponseBody;
 8 
 9 @Controller
10 @EnableAutoConfiguration
11 public class SampleController {
12 
13     @RequestMapping("/")
14     @ResponseBody
15     String home() {
16         return "Hello World!";
17     }
18 
19     public static void main(String[] args) throws Exception {
20         SpringApplication.run(SampleController.class, args);
21     }
22 }
復制代碼

4. 構件並以java application方式運行這個帶main方法的類

5. 瀏覽器訪問http://localhost:8080/,即可顯示Hello World

=================================================

簡單解釋一下相關

1. spring-boot-starter-parent:

springboot官方推薦的maven管理工具,最簡單的做法就是繼承它。 spring-boot-starter-parent包含了以下信息:

1)、缺省使用java6編譯, 如果需要改為java 1.7,則在pom中加上java.version屬性即可

2)、使用utf-8編碼

3)、實現了通用的測試框架 (JUnit, Hamcrest, Mockito).

4)、智能資源過濾

5)、智能的插件配置(exec plugin, surefire, Git commit ID, shade).

2. spring-boot-starter-web

springboot內嵌的WEB容器, 缺省會使用tomcat

3. @Controller

Java中的注解@Controller會啟動一個Spring MVC的控制器, 

4. @EnableAutoConfiguration

@EnableAutoConfiguration也是必須的,它用於開啟自動配置

5. @RequestMapping

示例中該注解將”/"映射到處理Hello world 輸出的home()方法

6. @ResponseBody

示例中該注解將home()的輸出字符串“Hello world”直接作為http request的響應內容,而不是Spring MVC中常用的視圖名字

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM