使用Spring Boot和Angular创建一个新的应用程序

Spring Boot作为Angular应用程序的后端非常有用,但是很难让它滚动。大多数Spring用户都熟悉Java以及用于创建和构建后端服务器的工具。前端可以使用普通的JavaScript编写,只要它相对简单,并且您愿意以这种方式搜索罕见的示例和教程。但是,你这些天更容易找到文档和使用工具,如教程Typescriptnode.jsnpm和角CLI。

本文将向您展示如何执行此操作并保持Spring Boot应用程序的完整性。大多数建议同样适用于其他前端框架(任何可以使用npm或类似构建的框架)。我们使用Maven,但Gradle用户可以使用类似的工具。我们的目标是拥有一个具有Spring Boot和Angular的应用程序,这个应用程序可以由任何了解这两种生态系统的人构建和开发,并且不会感到任何尴尬或单一。

创建一个Spring Boot应用程序

无论您通常如何创建新的Spring Boot应用程序,都要这样做。例如,您可以使用IDE功能。或者您可以在命令行上执行此操作:

$ curl start.spring.io/starter.tgz -d dependencies=web | tar -zxvf -
$ ./mvnw install

现在我们将采用该应用程序并添加一些Angular脚手架。在我们对Angular做任何事情之前,我们必须安装npm

在本地安装Npm

安装npm充满了问题,包括但不限于如何使其作为构建自动化的一部分工作。我们将使用Eirik Sletteberg 的优秀Maven Frontend插件。第一步是将它添加到我们的pom.xml

的pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.github.eirslett</groupId>
            <artifactId>frontend-maven-plugin</artifactId>
            <version>1.6</version>
            <configuration>
                <nodeVersion>v8.8.1</nodeVersion>
            </configuration>
            <executions>
                <execution>
                    <id>install-npm</id>
                    <goals>
                        <goal>install-node-and-npm</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

接着

$ ./mvnw generate-resources
$ ls node*

已经在顶级目录中安装了大量内容。下载的文件缓存在本地Maven存储库中后,每次构建运行它都不会花费很长时间。

安装Angular CLI

现在要构建一个Angular应用程序,使用Angular团队提供的CLI确实很有帮助。我们可以使用npm我们刚刚使用插件安装它。首先创建一个方便的脚本以npm从本地安装运行(如果您的路径上有其他人):

$ cat > npm
#!/bin/sh
cd $(dirname $0)
PATH="$PWD/node/":$PATH
node "node/node_modules/npm/bin/npm-cli.js" "$@"
$ chmod +x npm

然后运行它来安装CLI:

$ ./npm install @angular/cli

然后为CLI本身创建一个类似的包装器,并快速测试它:

$ cat > ng
#!/bin/sh
cd $(dirname $0)
PATH="$PWD/node/":"$PWD":$PATH
node_modules/@angular/cli/bin/ng "$@"
$ chmod +x ng
$ ./ng --version
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
           |___/
Angular CLI: 6.0.8
Node: 9.11.2
OS: linux x64
...

创建一个角度应用程序

Angular CLI可用于生成新的应用程序脚手架以及其他内容。这是一个有用的起点,但你现在可以抓住任何现有的Angular应用程序并将它放在同一个地方。我们希望在顶级目录中使用Angular应用程序以保持所有工具和IDE的快乐,但我们也希望使它看起来像常规的Maven构建。

使用CLI创建应用程序:

$ ./ng new client # add --minimal here if you want to skip tests

然后将其移动到项目的根目录中:

$ cat client/.gitignore >> .gitignore
$ rm -rf client/node* client/src/favicon.ico client/.gitignore client/.git
$ sed -i '/node_/anode/' .gitignore
$ cp -rf client/* .
$ cp client/.??* .
$ rm -rf client
$ sed -i -e 's,dist/client,target/classes/static,' angular.json

我们放弃了CLI安装的节点模块,因为我们希望前端插件能够在自动构建中为我们完成这项工作。我们还编辑了angular.json(有点像pom.xmlAngular CLI应用程序),将Angular构建的输出指向将打包在JAR文件中的位置。

建造

添加执行以安装应用程序中使用的模块:

<execution>
    <id>npm-install</id>
    <goals>
        <goal>npm</goal>
    </goals>
</execution>

使用再次安装模块./mvnw generate-resources并检查结果(版本会因您而异)。

$ ./ng version
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
           |___/
Angular CLI: 6.0.8
Node: 9.11.2
OS: linux x64
Angular: <error>
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.6.8
@angular-devkit/build-angular   <error>
@angular-devkit/core            0.6.8
@angular-devkit/schematics      0.6.8
@angular/cli                    6.0.8
@schematics/angular             0.6.8
@schematics/update              0.6.8
rxjs                            6.2.1
typescript                      2.7.2

此时,测试工作:

$ ./ng e2e
..
[13:59:46] I/direct - Using ChromeDriver directly...
Jasmine started

  client App
✓ should display welcome message

Executed 1 of 1 spec SUCCESS in 0.718 sec.
[13:59:48] I/launcher - 0 instance(s) of WebDriver still running
[13:59:48] I/launcher - chrome #01 passed

如果你也加上这个:

    <execution>
        <id>npm-build</id>
        <goals>
            <goal>npm</goal>
        </goals>
        <configuration>
            <arguments>run-script build</arguments>
        </configuration>
    </execution>

然后客户端应用程序将在Maven构建期间编译。

稳定构建

如果你想要一个稳定的构建,你应该在你^的版本之前放一个。当您执行此操作时,默认情况下不会添加它,但它可以保护您免受CLI中的更改。例:@angular/clipackage.jsonng new

的package.json

...
"devDependencies": {
    "@angular/cli": "^1.4.9",
...

开发时间

你可以持续建立

$ ./ng build --watch

更新(快速)构建并推送到target/classesSpring Boot可以获取的位置。您的IDE可能需要进行调整以自动获取更改(Spring Tool Suite开箱即用)。

真的,但是我们可以快速查看一些额外的东西,这些东西可以让你快速使用Spring Boot和Angular。

VSCode

Microsoft VSCode是开发JavaScript应用程序的一个很好的工具,它也对Java和Spring Boot有很好的支持。如果您安装“Java Extension Pack”(来自Microsoft),“Angular Essentials”(来自Jon Papa)和“最新TypeScript和JavaScript语法”(来自Microsoft),您将能够执行代码完成和源代码导航。 Angular app(所有这些扩展,可从IDE中发现)。您还需要下载并安装一些Spring Boot功能(在Extensions视图中单击右上角并选择Install from VSIX…​),地址为http://dist.springsource.com/snapshot/STS4/nightly-distributions.html

VSCode目前没有的是npm在项目本身中自动检测构建工具(.我们需要它,因此我们需要它)。因此,要从IDE构建,您可能需要添加.vscode/tasks.json如下内容:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "ng-build",
            "type": "shell",
            "command": "./ng build"
        },
        {
            "label": "ng-watch",
            "type": "shell",
            "command": "./ng build --watch"
        }
    ]
}

有了它,您的Tasks→Run Task…​菜单应该包含ng-watch选项,它将为您运行角度构建,并在您进行更改时重新编译。您可以添加其他条目以运行测试。

添加Bootstrap

您可以添加基本的Twitter Bootstrap功能,使应用程序看起来不那么枯燥(取自此博客):

$ ./npm install bootstrap@3 jquery --save

并更新styles.css以添加新内容:

styles.css的

@import "~bootstrap/dist/css/bootstrap.css";

基本角度特征

默认的脚手架应用程序中包含一些基本功能,包括HTTP客户端,HTML表单支持和使用导航的导航Router。所有这些都在angular.io中得到了极好的记录,互联网上有成千上万的例子说明如何使用这些功能。

举个例子,让我们看看如何添加HTTP客户端调用,并将其连接到Spring @RestController。在前端app-root组件中,我们可以为动态内容添加一些占位符:

app.component.html:

<div style="text-align:center"class="container">
  <h1>
    Welcome {{title}}!
  </h1>
  <div class="container">
    <p>Id: <span>{{data.id}}</span></p>
    <p>Message: <span>{{data.content}}</span></p>
  </div>
</div>

所以我们正在寻找data组件范围内的对象:

app.component.ts:

import { Component } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Demo';
  data = {};
  constructor(private http: HttpClient) {
    http.get('resource').subscribe(data => this.data = data);
  }
}

注意如何将AppComponent一个HttpClient注入到它的构造函数中。在模块定义中我们也需要导入HttpClientModule,以启用依赖注入:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

在我们的Spring Boot应用程序中,我们需要为/resource请求提供服务并使用正确的密钥为客户端返回一个对象:

DemoApplication.java:

@SpringBootApplication
@Controller
public class DemoApplication {

  @GetMapping("/resource")
  @ResponseBody
  public Map<String, Object> home() {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("id", UUID.randomUUID().toString());
    model.put("content", "Hello World");
    return model;
  }

...

}

如果你看一下Github中的源代码你也会注意到有一个后端交互测试app.component.spec.ts(感谢这个Ninja Squad博客)。在pom.xml已被修改,同时作为Java测试运行角度端对端测试。

结论

我们创建了一个Spring Boot应用程序,为它添加了一个简单的HTTP端点,然后使用Angular为它添加了一个前端。Angular应用程序是自包含的,因此任何知道这些工具的人都可以从自己的目录中使用它。Spring Boot应用程序将Angular资产折叠到其构建中,开发人员可以通过以常规方式运行应用程序,从常规IDE轻松更新和测试前端。

原文地址:https://github.com/dsyer/spring-boot-angular

注意:

原文的代码缺少主类,增加以下类后可以用 mvn spring-boot:run 命令运行:

package demo;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@SpringBootApplication
@Controller
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @GetMapping("/resource")
    @ResponseBody
    public Map<String, Object> home() {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
    }

}

运行结果:

猜你喜欢

转载自blog.csdn.net/daqiang012/article/details/81566431