最近有寫一個電子訂單商務網站,使用JAVA8,SPRING,ANGULARJS對項目使用的技術和大家分享。
第一次寫博客,哪有不對需要改正的請聯系改正。
因為是項目是我給別人做的無法提供源碼見諒,我盡最大努力讓大家能看懂。
首先從項目的構建開始,我采用的gradle構建項目,使用的版本是2.4。
開發環境用的IDEA 14,項目數據庫使用的是SQL SERVER。
Spring Boot 技術文檔:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle
你可以在這里查看所有Boot的配置與技術開發,對於英文不好的建議大致了解,我后面會慢慢寫出來,慢慢了解,把我所知道的。
如何把spring boot 引入項目如下:
先看下Gradle Spring Boot 配置,采用的版本是最新1.2.3
buildscript {
ext {
springBootVersion = "1.2.3.RELEASE"
}
repositories {
mavenLocal()
jcenter()
maven { url "http://repo.spring.io/snapshot" }
maven { url "http://repo.spring.io/milestone" }
maven { url "http://repo.spring.io/plugins-release"}
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("org.springframework:springloaded:${springBootVersion}")
classpath("org.springframework.build.gradle:propdeps-plugin:0.0.6")
}
}
apply plugin: "java"
apply plugin: "spring-boot"
這是一個gradle 基本的build.gradle配置文件。詳細你可以到gradle官網去了解使用它,跟它相同功能的有maven工具。Spring是支持這兩個插件構建的。
配置我們項目使用的spring 組件:
它在build.gradle文件代碼如下
dependencies { compile("org.springframework.boot:spring-boot-starter-web") testCompile("org.springframework.boot:spring-boot-starter-test") }
我們來看dependencies里面的內容,compile是gradle里面一個綁定資源方法,它可以把我們需要的資源包以及依賴去加載項目里面。如果你使用IDEA14它會自動幫你配置,引用類,一切都是那么簡單。
首先我們增加spring 的spring-boot-starter-web組件到項目里面。
使用spring boot:
Spring boot 是一個高集成化對spring管理工具,它可以將spring的組件協調處理,讓你花更少的時間去配置spring.
首先我們在項目根目錄包src/main/java/com/demo/下創建一個Application.java類,應該是這樣的:
@SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@SpringBootApplication 這是spring boot 入口。
我們寫一個實體Bean,src/main/java/com/demo/ Greeting.java 如下:
package com.demo; public class Greeting { private final long id; private final String content; public Greeting(long id, String content) { this.id = id; this.content = content; } public long getId() { return id; } public String getContent() { return content; } }
接下來我們寫一個簡單的控制器controller,src/main/java/com/demo/GreetingController.java 如下:
package com.demo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.atomic.AtomicLong; @RestController public class GreetingController { private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, name)); } }
@RestController表示這個控制器是rest的控制器,那么它返回的不是我們常見的VIEW對象,它會自動把對象JSON,這是spring 默認的,后面會介紹如何返回其他類型(XML,excel,FILE)
到這里我們已經寫了一個簡單的spring boot應用了。
運行spring boot 應用:
在IDEA里面我們可以直接點擊Application類右鍵直接運行,但是這樣做我們不推薦,因為這樣運行你只是運行了本地的目錄配置,沒有用到spring boot的。
我們使用gradle 構建所以我們更推薦你使用gradle 去運行你的項目。在IDEA 里面右邊你會找到gradle 的顯示窗口。就像剛一開始我們把spring boot 組件已經應用,gradle 配置文件build.gradle里面了。
apply plugin: 'java' apply plugin: 'idea' apply plugin: 'spring-boot'
所以我們應該可以在gradle的tasks里面找到application的程序組件。它們通常是這樣的:
而我們點擊bootRun 去運行它。
接下來我們在瀏覽器訪問
應該是這樣的。表示我們簡單的spring boot運行成功了。
下次我會更加深入講解,spring boot ,spring security,spring data 以及它的rest和jpa. 對於項目里面使用的JAVA8 也會涉及一些
http://www.cnblogs.com/jasonbob/p/4524385.html#undefined
Spring Boot 是由 Pivotal 團隊提供的全新框架,其設計目的是用來簡化新 Spring 應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。
本文主要是記錄使用 Spring Boot 和 Gradle 創建項目的過程,其中會包括 Spring Boot 的安裝及使用方法,希望通過這篇文章能夠快速搭建一個項目。
1. 開發環境
- 操作系統: mac
- JDK:1.7.0_60
- Gradle:2.2.1
- IDE:Idea
2. 創建項目
你可以通過 Spring Initializr 來創建一個空的項目,也可以手動創建,這里我使用的是手動創建 gradle 項目。
參考 使用Gradle構建項目 創建一個 ng-spring-boot 項目,執行的命令如下:
$ mkdir ng-spring-boot && cd ng-spring-boot $ gradle init
ng-spring-boot 目錄結構如下:
➜ ng-spring-boot tree
.
├── build.gradle
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
2 directories, 6 files
然后修改 build.gradle 文件:
buildscript { ext { springBootVersion = '1.2.2.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'spring-boot' jar { baseName = 'ng-spring-boot' version = '0.0.1-SNAPSHOT' } sourceCompatibility = 1.7 targetCompatibility = 1.7 repositories { mavenCentral() maven { url "https://repo.spring.io/libs-release" } } dependencies { compile("org.springframework.boot:spring-boot-starter-data-jpa") compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-actuator") runtime("org.hsqldb:hsqldb") testCompile("org.springframework.boot:spring-boot-starter-test") } eclipse { classpath { containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER') containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7' } } task wrapper(type: Wrapper) { gradleVersion = '2.3' }
使用 spring-boot-gradle-plugin 插件可以提供一些創建可執行 jar 和從源碼運行項目的任務,它還提供了 ResolutionStrategy
以方便依賴中不用寫版本號。
3. 創建一個可執行的類
首先,新建一個符合 Maven 規范的目錄結構:
$ mkdir -p src/main/java/com/javachen
創建一個 Sping boot 啟動類:
package com.javachen; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
main 方法使用了 SpringApplication 工具類。這將告訴Spring去讀取 Application 的元信息,並在Spring的應用上下文作為一個組件被管理。
-
@Configuration
注解告訴 spring 該類定義了 application context 的 bean 的一些配置。 -
@ComponentScan
注解告訴 Spring 遍歷帶有@Component
注解的類。這將保證 Spring 能找到並注冊 GreetingController,因為它被@RestController
標記,這也是@Component
的一種。 -
@EnableAutoConfiguration
注解會基於你的類加載路徑的內容切換合理的默認行為。比如,因為應用要依賴內嵌版本的 tomcat,所以一個tomcat服務器會被啟動並代替你進行合理的配置。再比如,因為應用要依賴 Spring 的 MVC 框架,一個 Spring MVC 的 DispatcherServlet 將被配置並注冊,並且不再需要 web.xml 文件。 -
你還可以添加
@EnableWebMvc
注解配置 Spring Mvc。
上面三個注解還可以用 @SpringBootApplication 代替:
package com.javachen.examples.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
你也可以修改該類的 main 方法,獲取 ApplicationContext:
package com.javachen; import java.util.Arrays; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @SpringBootApplication public class Application { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(Application.class, args); System.out.println("Let's inspect the beans provided by Spring Boot:"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.println(beanName); } } }
4. 創建一個實體類
創建一個實體類 src/main/java/com/javachen/model/Item.java:
package com.javachen.model; import javax.persistence.*; @Entity public class Item { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; @Column private boolean checked; @Column private String description; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
5. 創建控制類
創建一個 Restfull 的控制類,該類主要提供增刪改查的方法:
package com.javachen.controller; import com.javachen.model.Item; import com.javachen.repository.ItemRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.persistence.EntityNotFoundException; import java.util.List; @RestController @RequestMapping("/items") public class ItemController { @Autowired private ItemRepository repo; @RequestMapping(method = RequestMethod.GET) public List<Item> findItems() { return repo.findAll(); } @RequestMapping(method = RequestMethod.POST) public Item addItem(@RequestBody Item item) { item.setId(null); return repo.saveAndFlush(item); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public Item updateItem(@RequestBody Item updatedItem, @PathVariable Integer id) { Item item = repo.getOne(id); item.setChecked(updatedItem.isChecked()); item.setDescription(updatedItem.getDescription()); return repo.saveAndFlush(item); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.NO_CONTENT) public void deleteItem(@PathVariable Integer id) { repo.delete(id); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = { EmptyResultDataAccessException.class, EntityNotFoundException.class }) public void handleNotFound() { } }
Greeting 對象會被轉換成 JSON 字符串,這得益於 Spring 的 HTTP 消息轉換支持,你不必人工處理。由於 Jackson2 在 classpath 里,Spring的 MappingJackson2HttpMessageConverter
會自動完成這一工作。
這段代碼使用 Spring4 新的注解:@RestController
,表明該類的每個方法返回對象而不是視圖。它實際就是 @Controller
和 @ResponseBody
混合使用的簡寫方法。
6. 創建 JPA 倉庫
使用 JAP 來持久化數據:
package com.javachen.repository; import com.javachen.model.Item; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; public interface ItemRepository extends JpaRepository<Item, Integer> { @Query("SELECT i FROM Item i WHERE i.checked=true") List<Item> findChecked(); }
Spring Boot 可以自動配置嵌入式的數據庫,包括 H2、HSQL 和 Derby,你不需要配置數據庫鏈接的 url,只需要添加相關的依賴即可。另外,你還需要依賴 spring-jdbc,在本例中,我們是引入了對 spring-boot-starter-data-jpa 的依賴。如果你想使用其他類型的數據庫,則需要配置 spring.datasource.*
屬性,一個示例是在 application.properties 中配置如下屬性:
spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.jdbc.Driver
創建 src/main/resources/application.properties 文件,修改 JPA 相關配置,如:
spring.jpa.hibernate.ddl-auto=create-drop
注意:
SpringApplication 會在以下路徑查找 application.properties 並加載該文件:
- /config 目錄下
- 當前目錄
- classpath 中 /config 包下
- classpath 根路徑下
7. 運行項目
可以在項目根路徑直接運行下面命令:
$ export JAVA_OPTS=-Xmx1024m -XX:MaxPermSize=128M -Djava.security.egd=file:/dev/./urandom $ ./gradlew bootRun
也可以先 build 生成一個 jar 文件,然后執行該 jar 文件:
$ ./gradlew build && java -jar build/libs/ng-spring-boot-0.0.1-SNAPSHOT.jar
啟動過程中你會看到如下內容,這部分內容是在 Application 類中打印出來的:
Let's inspect the beans provided by Spring Boot:
application
beanNameHandlerMapping
defaultServletHandlerMapping
dispatcherServlet
embeddedServletContainerCustomizerBeanPostProcessor
handlerExceptionResolver
helloController
httpRequestHandlerAdapter
messageSource
mvcContentNegotiationManager
mvcConversionService
mvcValidator
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.context.embedded.properties.ServerProperties
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
propertySourcesBinder
propertySourcesPlaceholderConfigurer
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
simpleControllerHandlerAdapter
tomcatEmbeddedServletContainerFactory
viewControllerHandlerMapping
你也可以啟動遠程調試:
$ ./gradlew build $ java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n \ -jar build/libs/spring-boot-examples-0.0.1-SNAPSHOT.jar
接下來,打開瀏覽器訪問 http://localhost:8080/items,你會看到頁面輸出一個空的數組。然后,你可以使用瀏覽器的 Restfull 插件來添加、刪除、修改數據。
8. 添加前端庫文件
這里主要使用 Bower 來管理前端依賴,包括 angular 和 bootstrap。
配置 Bower ,需要在項目根目錄下創建 .bowerrc 和 bower.json 兩個文件。
.bowerrc 文件制定下載的依賴存放路徑:
{ "directory": "src/main/resources/static/bower_components", "json": "bower.json" }
bower.json 文件定義依賴關系:
{ "name": "ng-spring-boot", "dependencies": { "angular": "~1.3.0", "angular-resource": "~1.3.0", "bootstrap-css-only": "~3.2.0" } }
如果你沒有安裝 Bower,則運行下面命令進行安裝:
npm install -g bower
安裝之后下載依賴:
bower install
運行成功之后,查看 src/main/resources/static/bower_components 目錄結構:
src/main/resources/static/bower_components
├── angular
├── angular-resource
└── bootstrap-css-only
9. 創建前端頁面
注意:
前端頁面和 js 存放到 src/main/resources/static/ 目錄下,是因為 Spring Boot 會自動在 /static 或者 /public 或者 /resources 或者 /META-INF/resources 加載靜態頁面。
創建 index.html
創建 src/main/resources/static 目錄存放靜態頁面 index.html:
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="./bower_components/bootstrap-css-only/css/bootstrap.min.css" /> </head> <body ng-app="myApp"> <div class="container" ng-controller="AppController"> <div class="page-header"> <h1>A checklist</h1> </div> <div class="alert alert-info" role="alert" ng-hide="items && items.length > 0"> There are no items yet. </div> <form class="form-horizontal" role="form" ng-submit="addItem(newItem)"> <div class="form-group" ng-repeat="item in items"> <div class="checkbox col-xs-9"> <label> <input type="checkbox" ng-model="item.checked" ng-change="updateItem(item)"/> </label> </div> <div class="col-xs-3"> <button class="pull-right btn btn-danger" type="button" title="Delete" ng-click="deleteItem(item)"> <span class="glyphicon glyphicon-trash"></span> </button> </div> </div> <hr /> <div class="input-group"> <input type="text" class="form-control" ng-model="newItem" placeholder="Enter the description..." /> <span class="input-group-btn"> <button class="btn btn-default" type="submit" ng-disabled="!newItem" title="Add"> <span class="glyphicon glyphicon-plus"></span> </button> </span> </div> </form> </div> <script type="text/javascript" src="./bower_components/angular/angular.min.js"></script> <script type="text/javascript" src="./bower_components/angular-resource/angular-resource.min.js"></script> <script type="text/javascript" src="./bower_components/lodash/dist/lodash.min.js"></script> <script type="text/javascript" src="./app/app.js"></script> <script type="text/javascript" src="./app/controllers.js"></script> <script type="text/javascript" src="./app/services.js"></script> </body> </html>
初始化 AngularJS
這里使用閉包的方式來初始化 AngularJS,代碼見 src/main/resources/static/app/app.js :
(function(angular) { angular.module("myApp.controllers", []); angular.module("myApp.services", []); angular.module("myApp", ["ngResource", "myApp.controllers", "myApp.services"]); }(angular));
創建 resource factory
代碼見 src/main/resources/static/app/services.js :
(function(angular) { var ItemFactory = function($resource) { return $resource('/items/:id', { id: '@id' }, { update: { method: "PUT" }, remove: { method: "DELETE" } }); }; ItemFactory.$inject = ['$resource']; angular.module("myApp.services").factory("Item", ItemFactory); }(angular));
創建控制器
代碼見 src/main/resources/static/app/controllers.js :
(function(angular) { var AppController = function($scope, Item) { Item.query(function(response) { $scope.items = response ? response : []; }); $scope.addItem = function(description) { new Item({ description: description, checked: false }).$save(function(item) { $scope.items.push(item); }); $scope.newItem = ""; }; $scope.updateItem = function(item) { item.$update(); }; $scope.deleteItem = function(item) { item.$remove(function() { $scope.items.splice($scope.items.indexOf(item), 1); }); }; }; AppController.$inject = ['$scope', 'Item']; angular.module("myApp.controllers").controller("AppController", AppController); }(angular));
10. 測試前端頁面
再一次打開瀏覽器,訪問 http://localhost:8080/ 進行測試。
11. 總結
本文主要是記錄快速使用 Spring Boot 和 Gradle 創建 AngularJS 項目的過程。,希望能對你有所幫助。
文中相關的源碼在 ng-spring-boot,你可以下載該項目,然后編譯、運行代碼。
該項目也可以使用 maven 編譯、運行:
$ mvn clean package $ java -jar target/ng-spring-boot-0.0.1-SNAPSHOT.jar
或者直接運行:
$ mvn spring-boot:run
11. 參考文章
- Rapid prototyping with Spring Boot and AngularJS
- Building an Application with Spring Boot
- Building a RESTful Web Service
- Enabling Cross Origin Requests for a RESTful Web Service
本文鏈接地址: http://blog.javachen.com/2015/01/06/build-app-with-spring-boot-and-gradle.html
本文基於 署名2.5中國大陸許可協議發布,歡迎轉載、演繹或用於商業目的,但是必須保留本文署名和文章鏈接。 如您有任何疑問或者授權方面的協商,請郵件聯系我。
http://www.cnblogs.com/mingjian/p/4680845.html