over 2 years ago

Spring Boot 在設定檔方面幫我們做好許多事,我們要做的大概就只有定義Class跟寫註解

注入一組字串List

設定檔

application.yml
CrawlerClassArray:

  - CrawlerApple

  - CrawlerYahoo

  - CrawlerEttoday

  - CrawlerChinatimes
CrawlerConfig.java
package com.sam.app;

import java.util.List;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties
public class CrawlerConfig {
    private List<String> crawlerClassArray;
}

使用方式

@Autowired
private CrawlerConfig crawlerConfig;

crawlerConfig.getCrawlerClassArray().forEach( classname -> System.out.println(classname));

結果頁

CrawlerApple
CrawlerYahoo
CrawlerEttoday
CrawlerChinatimes

如果你想注入一組有結構的資料

設定檔

application.yml
crawler:

  targets:

    -

      name: CrawlerApple

    -

      name: CrawlerYahoo

    -

      name: CrawlerEttoday

    -

      name: CrawlerChinatimes

    -

      name: GoogleAlert

      source: D:/stockalert.txt

定義資料對應的物件格式

CrawlerTarget.java
import lombok.Data;

@Data
public class CrawlerTarget {
    private String name;
    private String source;
}

設定檔對象

CrawlerConfig.java
import java.util.List;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix="crawler")
public class CrawlerConfig {
    private List<CrawlerTarget> targets;
}

使用的時候

@Autowired
private CrawlerConfig crawlerConfig;

crawlerConfig.getTargets().forEach( e -> System.out.println(e.toString()));

結果

CrawlerTarget(name=CrawlerApple, source=null)
CrawlerTarget(name=CrawlerYahoo, source=null)
CrawlerTarget(name=CrawlerEttoday, source=null)
CrawlerTarget(name=CrawlerChinatimes, source=null)
CrawlerTarget(name=GoogleAlert, source=D:/stockalert.txt)

結論上來說比xml更簡易了

20150826補充
變更執行的Port

application.yml
server:

  port: 8080

or

java -jar demo-0.0.1-SNAPSHOT.jar --server.port=9000
← 使用Vagrant跟Docker快速建構開發與測試環境 Ubuntu 安裝 FTP →
 
comments powered by Disqus