spring boot學習筆記


spring boot 是什么

Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。 
spring boot采用了“約定優於配置” 的理念,減少了spring繁瑣的配置,方便快速搭建應用 
spring boot官網:http://projects.spring.io/spring-boot/

maven配置:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

  

配置解讀:

  • 繼承spring-boot-starter-parent后我們可以繼承一些默認的依賴,這樣就無需添加一堆相應的依賴,把依賴配置最小化
  • spring-boot-starter-web提供了對web的支持,提供了嵌入式Tomcat容器以及端點信息:如服務器信息、應用指標(metrics)以及環境詳情

hello world

官網中的hello-world,示例如下:

package hello;

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

@Controller  // 標識是web的controller類
@EnableAutoConfiguration // 允許自動加載配置,Boot要采用一種特定的方式來對應用進行配置
public class SampleController {
    @RequestMapping("/") // 對應restful url的相對目錄
    @ResponseBody // 將返回直接作為response的body
    String home() {
        return "Hello World!";
    }

    // 啟動應用程序
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}
 

main分離

當如果有多個controller的時候,直接把main放在一個controller里面是不合適的,那么就把main單獨拆分出來

UserController.class:

package sailorxiao.SpringBootSample.controller; // 約定的controller都放在controller目錄下

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

@Controller
@RequestMapping("/user")
@EnableAutoConfiguration
public class UserController {
    public String helloUser() {
        return "Hello user!";
    }
}
main:

package sailorxiao.SpringBootSample; // 默認的main對應的class應該放在項目src代碼的一級目錄下,默認使用Application

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration
@ComponentScan
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

  

如圖所示,對於main函數,沒法放到單獨controller里面,因此:

  • @EnableAutoConfiguration 標志在對應的主要class上
  • @ComponentScan 允許boot依據約定的規則對項目中的bean進行掃描
 

增加@Autowired自動裝配

通常在controller中會有一些邏輯交互,需要做一些處理(比如讀寫db,進行一些業務邏輯等),一般會把相關的操作放到對應的service下,如下,對UserContrller進行處理,增加UserService 
UserController:

package sailorxiao.SpringBootSample.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import sailorxiao.SpringBootSample.entity.User;
import sailorxiao.SpringBootSample.service.IHelloService;
import sailorxiao.SpringBootSample.service.IUserService;

@RestController
public class UserController {
    @Autowired
    private IUserService userService; //使用了自動裝備,boot會自動裝配對應的service對象

    @RequestMapping("/hello/{name}") // rest path中帶着name,完整的url就是 http://xxxx/user/{name}
    public String helloUser(@PathVariable("name") String name) {
        return userService.helloUser(name);
    }
}

  

service目錄下

IUserService:

package sailorxiao.SpringBootSample.service; // 所有的service約定都放在service目錄下

public interface IUserService { // 對於每個service需要定義好一個interface,直接放在service目錄下,名字為IXXXService
    public String helloUser(String user);
}

  

IUserServiceImpl:

package sailorxiao.SpringBootSample.service.impl;

import org.springframework.stereotype.Component;
import sailorxiao.SpringBootSample.service.IUserService;

@Component // 需要加上這個標簽,這樣main的ComponentScan才能掃描到對應的實現
public class UserServiceImpl implements IUserService {
    @Override
    public String helloUser(String user) {
        return "hello " + user;
    }
}

http body 約束

很多時候,會希望傳入的是一些特定規則的參數,比如我們希望在UserController中傳入User對象{name:xxx,age:xxx} 
controller:

package sailorxiao.SpringBootSample.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import sailorxiao.SpringBootSample.entity.User;
import sailorxiao.SpringBootSample.service.IUserService;

@RestController
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/hello/{name}")
    public String helloUser(@PathVariable("name") String name) {
        return userService.helloUser(name);
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }
}

  

User對象:

package sailorxiao.SpringBootSample.entity; // 一般而言與用戶相關的對象都放在entity目錄下

public class User { // User對象是個bean,有默認的set/get方法
    private String name;
    private int age;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return this.age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

  

注意,在client使用json作為body傳遞給server的controller的時候,需要標志contentType是"application/json",如使用以下方式:

HttpClient httpClient = new HttpClient();

StringRequestEntity requestEntity = new StringRequestEntity(
        jsonStr, // json的序列化后的string,比如這里應該就是USER對象序列化成json的str
        "application/json",
        "UTF-8");

PostMethod postMethod = new PostMethod(url);
postMethod.setRequestEntity(requestEntity);

httpClient.executeMethod(postMethod);

String resStr = postMethod.getResponseBodyAsString();
System.out.println("post res: " + resStr);

resource

有時候需要使用配置,那么在boot里面使用配置非常簡單,如下,在定義配置后,只需要在程序中聲明 

application.properties:

host="192.168.137.10"
port=34001
properties類:

@ConfigurationProperties // 聲明這個是properties的bean
public class BootMongoProperties {
    private String host;
    private int port;
    public String getHost() {
        return this.host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public int getPort() {
        return this.port;
    }
    public void setPort(int port) {
        this.port = port;
    }
}

  

如果配置都是以一定名稱打頭的,可以加上prefix字段,如:

@ConfigurationProperties(prefix = "spring.data.mongodb")
    public class BootMongoProperties {
        private String host; //表示配置項為spring.data.mongodb.host
        private int port;
        private String uri = "mongodb://localhost/test"; // 如果配置中沒有配置spring.data.mongodb.uri的話,默認為該值
        public String getHost() {
            return this.host;
        }
        public void setHost(String host) {
            this.host = host;
        }
        public int getPort() {
            return this.port;
        }
        public void setPort(int port) {
            this.port = port;
        }
    }

mongodb支持

一般而言web服務中需要使用到db,那么在spring boot里面是如何進行db相關操作的呢?以mongodb為例只需要三部

第一步,配置db相關配置,如圖在application.properties中配置mongodb的uri

spring.data.mongodb.uri=mongodb://sailor:sailor@192.168.137.10:34001/sailor?autoConnectRetry=true&connectTimeout=60000
spring.data.mongodb.repositories.enabled=true

第二步,聲明mongoTemplate,mongodb的driver中,相關操作都是通過mongoTemplate進行的

@Resource  // @Resource表示mongoTemplate直接基於配置生成對應的mongoTemplate操作實例
private MongoTemplate mongoTemplate;

第三步,使用mongoTemplate

User user = new User(name, age); // 定義一個collection相關的bean
mongoTemplate.insert(user); // 從mongo中插入該數據,插入到user對應的類名的集合中(這里就是user)

User類:
    public class User {
        private String name;
        private int age;

        public User() {
            // do nothing
        }

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return this.name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return this.age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }

  

通過以上三步,就能很簡單得實現boot操作對應的db

 

問題

通過java -jar運行時,提示找不到main函數

解決方案,在pom.xml中加入mainClass選項,指明對應的mainClass

<build>
<plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <mainClass>SailorXiao.spring.main.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

  


免責聲明!

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



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