閱讀37 返回首頁    go 阿裏雲 go 技術社區[雲棲]


SpringBoot開發案例之奇技淫巧

程序員都有著一種天生的好奇心,這種好奇心引導著我們的編程生涯。寫幾行代碼,裝載到計算機裏,讓它按照你的思路工作,這是非常有趣的事情。但隨著開發的東西越來越多,我們變的越來越忙,這種好奇心會慢慢的減退。我們應該時不時的用一些新思路挑戰自己,讓自己的思想保持鋒銳和專注,提醒自己為什麼當初選擇碼農這條道路。

版本標注

小夥伴們可能會發現pom.xml中很多是沒有版本號的比如:

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

其實,在頭部我們加了以下配置:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/>
</parent>

spring-boot-starter-parent包含了大量配置好的依賴管理,在自己項目添加這些依賴的時候不需要寫版本號

熱部署

方法1 添加springloaded依賴

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>springloaded</artifactId>
     <version>1.2.5.RELEASE</version>
</dependency>

原理:基於ASM實現動態生成類或者增強既有類,每次類的修改會被檢測到,然後重新生成新的類並加載。如果不懂什麼是ASM可以百度JAVA-ASM。

方法2 添加spring-boot-devtools依賴

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
</dependency>

原理:spring-boot-devtools 是一個為開發者服務的一個模塊,其中最重要的功能就是自動應用代碼更改到最新的App上麵去。原理是在發現代碼有更改之後,重新啟動應用,但是速度比手動停止後再啟動還要更快,更快指的不是節省出來的手工操作的時間。其深層原理是使用了兩個ClassLoader,一個Classloader加載那些不會改變的類(第三方Jar包),另一個ClassLoader加載會更改的類,稱為 restart ClassLoader,這樣在有代碼更改的時候,原來的restart ClassLoader 被丟棄,重新創建一個restart ClassLoader,由於需要加載的類相比較少,所以實現了較快的重啟時間(5秒以內)。

配置文件

在 spring boot 中,有兩種方式實現文件配置,application.properties 和 application.yml。大家可能對properties 比較熟悉,而另一種yml是基於YAML實現的,YAML 是一種比JSON(json多層次{ 與 [ 會被搞暈的)更直觀的表現形式,展示上更易查錯和關係描述。因為不需要一個專業工具就可以排查正確性。

下麵,我們以server為例展示下兩者的不同。

application.properties

server.context-path=/springboot
server.port=8080
server.session-timeout=60
server.address=192.168.1.66

server.tomcat.max-threads=300
server.tomcat.uri-encoding=UTF-8

application.yml

server:
    context-path: /springboot
    port: 8080
    session-timeout: 60
    address: 192.168.1.66
    tomcat:
      max-threads: 300
      uri-encoding: UTF-8
logging:
    level:
      root: INFO

yml天然的樹狀結構,一目了然,層次感強,有沒有亮瞎你。當然使用yml要注意,層次間隔必須是空格不能是TAB,並且屬性名的值和冒號中間必須有空格。

部署環境

開發環境(development)
application-dev.properties

測試環境(test)
application-test.properties

生產環境(production)
application-prod.properties

那麼如何定義使用哪種配置文件呢?
  在主配置文件application.yml中配置如下:

spring:
  profiles:
    active: dev

屬性配置

如何在代碼中獲取配置文件中的屬性呢?spring-boot為我們提供了這樣一種方式,隻需要使用@Value注解即可。

@Value("${spring.mail.username}")
public String USER_NAME;

thymeleaf模版

默認配置下,thymeleaf對html的內容要求很嚴格,比如,如果少最後的標簽封閉符號/,就會報錯而轉到錯誤頁。

#忽略thymeleaf嚴格的校驗
spring.thymeleaf.mode=LEGACYHTML5

#開發階段設置為false方便調試
spring.devtools.livereload.enabled=true
spring.thymeleaf.cache=false
spring.thymeleaf.cache-period=0
spring.thymeleaf.template.cache=false

靜態資源

Spring Boot中靜態資源(JS, 圖片)等應該放在什麼位置?

Spring Boot能大大簡化WEB應用開發的原因, 最重要的就是遵循“約定優於配置”這一基本原則。Spring Boot的關於靜態資源的默認配置已經完全滿足絕大部分WEB應用的需求。沒必要去弄手續繁雜的自定義,用Spring Boot的約定就好了。

在Maven 工程目錄下,所有靜態資源都放在src/main/resource目錄下,結構如下:

src/main/resource
          |__________static
                        |_________js
                        |_________images
                        |_________css
                 .....

比如,我們引入以下css:

<link rel="stylesheet" th:href="@{css/alipay.css}" />

自定義靜態資源

通過配置文件配置

在application.properties(或.yml)中配置

# 靜態文件請求匹配方式
spring.mvc.static-path-pattern=/**
# 修改默認的靜態尋址資源目錄 多個使用逗號分隔
spring.resources.static-locations = classpath:/templates/,classpath:/resources/,classpath:/static/

通過代碼配置

@EnableAutoConfiguration
@ComponentScan(basePackages = { "com.itstyle.modules" })
public class Application extends WebMvcConfigurerAdapter {
    private static final Logger logger = Logger.getLogger(Application.class);
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/cert/**").addResourceLocations(
                "classpath:/cert/");
        super.addResourceHandlers(registry);
        logger.info("自定義靜態資源目錄");
    }

    public static void main(String[] args) throws InterruptedException,
            IOException {
        SpringApplication.run(Application.class, args);
        logger.info("支付項目啟動 ");
    }

}

文件操作

獲取文件

File file = ResourceUtils.getFile("classpath:cert/readme.txt");

獲取路徑

ClassUtils.getDefaultClassLoader().getResource("cert").getPath()

Controller和RestController的區別?

官方文檔:
@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
意思是:
@RestController注解相當於@ResponseBody + @Controller合在一起的作用。

1)如果隻是使用@RestController注解Controller,則Controller中的方法無法返回jsp頁麵,配置的視圖解析器InternalResourceViewResolver不起作用,返回的內容就是Return 裏的內容。
例如:本來應該到success.jsp頁麵的,則其顯示success.

2)如果需要返回到指定頁麵,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
3)如果需要返回JSON,XML或自定義mediaType內容到頁麵,則需要在對應的方法上加上@ResponseBody注解。

作者: 小柒

出處: https://blog.52itstyle.com

本文版權歸作者和雲棲社區所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁麵明顯位置給出, 如有問題, 可郵件(345849402@qq.com)谘詢。

最後更新:2017-08-13 22:42:45

  上一篇:go  Oculus也陷隱私門:向Facebook發送隱私數據
  下一篇:go  正確使用Android性能分析工具——TraceView