總網頁瀏覽量

關於我自己

我的相片
人生的必修課是接受無常,人生的選修課是放下執著。

2014年10月14日 星期二

STS(Spring Tool Suite) 建立 Gradle Project


  • 修改 STS.ini , 看看Xmx要不要加大C:\xxx\3.6.1\sts-bundle\sts-3.6.1.RELEASE\STS.ini
  • STS.ini加上下列預設值, 避免 gradle2 的 bug
    -Dosgi.configuration.area.default=null
    -Dosgi.user.area.default=null
    -Dosgi.user.area=@user.dir
  • 啟動 STS
  • 建立一個gradle project
    File > New > Project
  •  Gradle > Gradle Project
    輸入 Project name
    Sample project選Java Quickstart


  •  
*此時新建好的Gradle Project沒error(紅字)



  • 下載新的build.gradle
    https://www.evernote.com/shard/s386/sh/343c559e-2422-46a6-9fdb-72ccc3570dc9/844b3db026522687/res/0cb7e2d5-552f-45b7-b3be-ac8f0f5b4398/build.gradle
  • 找到剛建立Gradle project位置
    例如:
    C:\使用者\xxxx\Documents\workspace-sts-3.6.2.RELEASE\GP
  • 蓋過原始的 build.gradle
  • project上按右鍵 > Gradle > Reflash All
    就會開始下載相依 lib
    要注意 :  不要用公司OA網路, proxy怪怪

  • 下載成功後看到如下訊息

      *此時新建好的Gradle Project有error(紅字)
       project滑鼠按右鍵>Gradle>在Gradle點一下enable DSL support紅字就不見ㄌ
  •  
  •  設定Spring ide 相關開發界面
  • Window > preferences > spring > Validation > Project Validator > 展開Bean Validator > Annotation-based Autowiring Rule 打勾
  • 專案按右鍵 > Properties > 展開Spring > Beans Support > 找到Config Files > Enable support for <import/> element in configuration files 打勾 
  • 專案按右鍵 > spring > beans support > 找到Config Detection > Auto detection for annotated Java Spring configuration files 打勾
  • 就可以在 spring perspective 看到bean, requestmapping 等列表
  •  
  • 建立package : 在src/main/java點滑鼠右鍵>New>Package>取名為 tw.net.xxxxxxx.api2.hello
  • tw.net.xxxxxxx.api2.hello點滑鼠右鍵>New>Class>取名為HelloController
  • 內容:
  • package tw.net.xxxxxxx.api2.hello;

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;

    @Controller
    public class HelloController {

        @RequestMapping("/hello/{who}")
        public @ResponseBody String hello(
                @PathVariable String who,
                @RequestParam(value = "gender", required = false, defaultValue = "Mr.") String gender,
                Model model) {

            return " hello " + gender + ' ' + who;

        }
  • }
  • 說明:
  • method 直接回傳 String , 並說它是@ResponseBody
  • @PathVariable 用來收url內嵌變數
  • @RequestParam 用來收request變數

  • tw.net.xxxxxxx.api2.hello點滑鼠右鍵>New>Class>取名為Application
  • 內容: 
  • package tw.net.xxxxxxx.api2.hello;

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

    @Configuration
    @ComponentScan
    // @EnableAutoConfiguration
    @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
    public class Application {

        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
            // TODO Auto-generated method stub

        }

    }

     
  • 說明:
  • (src/main/java/tw/net/mymusic/api2/Application.java)
    • 指定它可以宣告設定 : @Configuration
    • 指定它可以自動掃描 bean : @ComponentScan
    • 指定它可以以預設直補齊相關config :@EnableAutoConfiguration
    • @EnableAutoConfiguration (exclude = { DataSourceAutoConfiguration. class })
      因為沒有datasource設定或使用內建db , 所以先把 datasource自動 config 停掉
  •  
  •   
  •  
  • build 一個含embedded tomcat 的 runnable jar
  • 專案按右鍵 > Gradle > Task Quick Launcher > 輸入 build > enter後會產生錯誤訊息
  • There were failing tests. See the report at: file:///home/freeman/workspace_STS/GP/build/reports/tests/index.html
    Could not execute build using Gradle distribution 'https://services.gradle.org/distributions/gradle-2.1-bin.zip'. 
  • 解法:開啟~\workspace-sts-3.6.2.RELEASE\GP2\gradle.build
  • 在最下面加上一段 
  • dependencies {
        compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
        testCompile group: 'junit', name: 'junit', version: '4.+'
     
  • 回到STS,  專案按右鍵 > Gradle > Refresh All 
  • 專案按右鍵 > Gradle > Task Quick Launcher > 輸入 build > 按下enter鍵
  • *如果還是出現error, 關掉STS重新開啟, 再重複一次步驟 
  • 成功後在專案\build\lib\可看到產生api2-xxxxxxx-server-0.1.0.jar
  •  
  • 第二種測試方法:用不同的啟動參數測試
  • 打開命令提示字元 > 路徑切換至 ~\專案\build\lib\
  •  輸入java -Dserver.port=8888 -jar api2-xxxxxxx-server-0.1.0.jar
  • C:\Users\使用者\Documents\workspace-sts-3.6.2.RELEASE\GP3\build\libs>java -
    Dserver.port=8888 -jar api2-xxxxxxx-server-0.1.0.jar

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v1.1.6.RELEASE)
  • 測試url就要用http://127.0.0.1:8888/hello/Justin Lee
  • 輸入java -Dserver.port=8880 -jar api2-xxxxxxx-server-0.1.0.jar測試
  • 測試url就要用http://127.0.0.1:8880/hello/Methanna?gender=Miss
Talk to DB

專案/src/main/resources建立application.propertie,內容
#spring.thymeleaf.cache=false
#server.port=${xxxxxxx.api.port}
#management.port=${xxxxxxx.adm.port}
#management.address=127.0.0.1

# Data Source
spring.datasource.url=jdbc:mysql://127.0.0.1:8306/shop_queue
spring.datasource.username=demoo
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.max-active=50
spring.datasource.max-idle=10
spring.datasource.min-idle=10
spring.datasource.initial-size=10

datasource.secondary.url=jdbc:mysql://127.0.0.1:8306/yii_test
datasource.secondary.username=demoo
datasource.secondary.password=123456
datasource.secondary.driverClassName=com.mysql.jdbc.Driver
datasource.secondary.max-active=50
datasource.secondary.max-idle=10
datasource.secondary.min-idle=10
datasource.secondary.initial-size=10


專案/src/main/java建立封包tw.net.xxxxxxx.api2.hello.cfg再建DataSourceConfig.java
package tw.net.xxxxxxx.api2.hello.cfg;

import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class DataSourceConfig extends DataSourceAutoConfiguration {

    @Bean(name = "ds2")
    @ConfigurationProperties(prefix = "datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "jdbc2")
    public JdbcTemplate jdbcTemplate2(DataSource ds2) {
        return new JdbcTemplate(ds2);
    }

}

結果就像下面這樣
接著在專案/src/main/java/tw.net.xxxxxxx.api2.hello/建立HelloDao.java,內容
package tw.net.xxxxxxx.api2.hello;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class HelloDao {

    private Log logger = LogFactory.getLog(getClass());

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    @Qualifier("jdbc2")
    private JdbcTemplate jdbc2;

    public String getListFromDsDefault() {
        String rtn = "";

        List<Map<String, Object>> results = (List<Map<String, Object>>) jdbcTemplate
                .queryForList("SELECT bat_no FROM order_import_detail LIMIT 5");

        for (Map<String, Object> result : results) {
            String batNo = (String) result.get("bat_no");

            rtn += (batNo + "<br>");
        }
        return rtn;
    }

    public String getListFromDsDefault2() {
        String rtn = "";
        List<Map<String, Object>> results = (List<Map<String, Object>>) jdbc2
                .queryForList("SELECT username,email FROM tbl_user LIMIT 5");

        for (Map<String, Object> result : results) {
            String username = (String) result.get("username");
            String email = (String) result.get("email");

            rtn += (username + " >> " + email + "<br>");
        }

        return rtn;
    }

}

至於Application.java也稍做修改
package tw.net.xxxxxxx.api2.hello;

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

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        // TODO Auto-generated method stub

    }

}

 

再次測試→點擊http://127.0.0.1:8080/hello/kokoko?jdbc=yes
若成功會開啟網頁如下
若失敗則會讀不出網頁內容

用 Junit 測試 Bean

1. 先於 專案/src/test/java/建立package名為tw.net.xxxxxxx.api2.hello
2. 於專案/src/main/java/tw.net.xxxxxxx.api2.hello/HelloDao.java上按右鍵
New > JUnit Test Case > (1)選「New JUnit 4 test」 (2)選「Browse」路徑要專案/src/test/java (3)按「Next」去選擇要測試的項目

(4) 「Finish」後, 專案/src/test/java/tw.net.xxxxxxx.api2.hello/就會產生HelloDaoTest.java了


3. 於專案/src/main/java/tw.net.xxxxxxx.api2.hello/HelloContorller.java上按右鍵
New > JUnit Test Case > (1)選「New JUnit 4 test」 (2)選「Browse」路徑要專案/src/test/java (3)按「Next」去選擇要測試的項目 (4) 「Finish」後, 專案/src/test/java/tw.net.xxxxxxx.api2.hello/就會產生HelloContorllerTest.java了

4.但我們需要去修改HelloContorllerTest.java為
package tw.net.xxxxxxx.api2.hello;

import static org.junit.Assert.*;

import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.jayway.restassured.RestAssured;

import static com.jayway.restassured.RestAssured.*;
import static com.jayway.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;
import tw.net.mymusic.api2.Application;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class HelloControllerTest {

    @Value("${local.server.port}")
    int port;

    @Before
    public void setUp() throws Exception {
        RestAssured.port = port;
    }

    @Test
    public void testHello() {
        // fail("Not yet implemented");
        // hello/Eleanor?gender=Miss
        // when().get("/hello/Eleanor").then().assertThat().statusCode(HttpStatus.SC_OK);

        given().param("gender", "Miss").param("key2", "value2").when()
                .get("/hello/Eleanor").then().assertThat()
                .statusCode(HttpStatus.SC_OK)
                .body(containsString("hello Miss Eleanor"));
    }
}

 

5. 在HelloContorllerTest.java上按右鍵Run As > 4 JUnit Test ,檢視視窗如下,看有沒有執行成功

6. .body(containsString("hello Miss Eleanor"));←這個字串與http://127.0.0.1:8080/hello/Eleanor?gender=Miss網頁執行的結果一樣,就是Pass;若不一樣,5.則是Fail


#################電腦關掉重啟後#######################
1.
  • 打開命令提示字元 > 路徑切換至 ~\專案\build\lib\
  •  輸入java -Dserver.port=8888 -jar api2-xxxxxxx-server-0.1.0.jar
  • C:\Users\使用者\Documents\workspace-sts-3.6.2.RELEASE\GP3\build\libs>java -
    Dserver.port=8888 -jar api2-xxxxxxx-server-0.1.0.jar

2. STS>HelloContorllerTest.java上按右鍵Run As > 4 JUnit Test ,檢視視窗如下,看有沒有執行成功

3. 開啟網頁http://127.0.0.1:8888/hello/Eleanor?gender=Miss看有無成功

沒有留言:

張貼留言