A Guide to Spring in Eclipse STS – Eclipse STS中的Spring指南

最后修改: 2016年 7月 13日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This article illustrates some of the useful features of the Eclipse Spring Tool Suite (STS) IDE, which are useful when developing Spring applications.

本文说明了Eclipse Spring Tool Suite (STS) IDE的一些有用功能,这些功能在开发Spring应用程序时非常有用。

First we show the benefits of using STS as compared to the traditional way of building applications with Eclipse.

首先我们展示了使用STS与使用Eclipse构建应用程序的传统方式相比的好处。

Thereafter, we focus on how to bootstrap an application, how to run it and how to add additional dependencies. Finally we conclude by adding application arguments.

此后,我们集中讨论了如何启动一个应用程序,如何运行它以及如何添加额外的依赖。最后,我们通过添加应用程序的参数来结束。

2. STS Main Features

2.STS的主要特点

STS is an Eclipse-based development environment that is customized for the development of Spring applications.

STS是一个基于Eclipse的开发环境,是为开发Spring应用程序而定制的。

It provides a ready-to-use environment to implement, debug, run and deploy your applications. It also includes integration for Pivotal tc Server, Pivotal Cloud Foundry, Git, Maven and AspectJ. STS is built as an addition on top of the latest Eclipse releases.

它提供了一个随时可用的环境来实现、调试、运行和部署你的应用程序。它还包括对Pivotal tc服务器、Pivotal Cloud Foundry、Git、Maven和AspectJ的集成。STS是在最新的Eclipse版本基础上建立起来的,是一种补充。

2.1. Project Configuration

2.1.项目配置

STS understands almost all of the most common Java project structures. It parses configuration files and then displays detailed information about beans that are defined, dependencies, used namespaces and in addition extracts overviews for certain stereotypes.

STS能够理解几乎所有最常见的Java项目结构。它解析配置文件,然后显示有关定义的Bean的详细信息、依赖关系、使用的命名空间,此外还可以提取某些定型的概述。

spring-bean-snapshot

2.2. STS Features Overview

2.2.STS功能概述

Eclipse STS validates your project and provides quick fixes for your applications. For example, when working with Spring Data JPA, the IDE may be used to validate query method names (more on this in section 6).

Eclipse STS会验证你的项目,并为你的应用程序提供快速修复。例如,在使用Spring Data JPA时,可以使用IDE来验证查询方法的名称(更多内容见第6节)。

STS also provides a graphical view on all bean methods and their mutual relationships. You may want to have a closer look at the graphical editors that come with STS by looking into the views that are available under the menus window, show view and then Spring respectively.

STS还提供了一个关于所有Bean方法及其相互关系的图形视图。你可能想通过查看菜单windowshow viewSpring下的视图来仔细了解一下STS附带的图形化编辑器。

STS also offers other additional useful features that are not limited to Spring applications only. The reader is recommended to a look at the full list of features that can be found here.

STS还提供了其他额外的有用功能,这些功能不仅限于Spring应用程序。建议读者查看完整的功能列表,该列表可以在这里找到。

3. Creation of a Spring Application

3.创建一个Spring应用程序

Let us start by bootstrapping a simple application. Without STS a Spring application is usually created by using the Spring Initializer website or the Spring Boot CLI. This may be simplified by clicking on Create Spring Starter Project from your dashboard in STS.

让我们从启动一个简单的应用程序开始。在没有STS的情况下,通常通过使用Spring Initializer 网站或Spring Boot CLI创建Spring应用程序。这可以通过点击STS中仪表板上的创建Spring Starter项目来简化。

In the New Spring Starter Project screen either use the defaults or make your own adjustments and then go to next screen. Select Web and click finish. Your pom.xml should now look similar to this:

New Spring Starter Project屏幕上,可以使用默认值或进行自己的调整,然后转到下一个屏幕。选择Web并点击完成。你的pom.xml现在应该类似于这样。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.0</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
		
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Your version of Spring Boot may be different but the latest version may always be found here.

您的Spring Boot版本可能不同,但最新的版本可以随时找到这里

4. Running the Application

4.运行应用程序

The aforementioned application may be started by right-clicking on the project and selecting run as Spring Boot App. Without STS, you will most likely run the application from the command-line with the following command:

上述应用程序可以通过右键单击项目并选择作为Spring Boot App运行来启动。如果没有STS,你很可能用以下命令从命令行运行该应用程序。

$ mvn spring-boot:run

By default Spring applications are started with Tomcat running on port 8080. At this point, the application starts on port 8080 and basically does nothing else as we did not implement any code yet. Section 8 shows you how to change the default port.

默认情况下,Spring应用程序是通过运行在8080端口的Tomcat启动的。此时,应用程序在8080端口启动,基本上不做其他事情,因为我们还没有实现任何代码。第8节告诉你如何改变默认端口。

5. Logging and ANSI Console

5.日志和ANSI控制台

When you run the project from the IDE using the run command, you will notice that the console outputs some nice color-coded log statements. In case you want to turn it off, go to run configurations… and disable the check box Enable ANSI console output on the Spring Boot tab. Alternatively you can also disable it by setting a properties value in the application.properties file.

当你使用运行命令从IDE运行该项目时,你会注意到控制台会输出一些漂亮的彩色编码的日志语句。如果您想关闭它,请进入运行配置…并禁用Spring Boot标签上的复选框启用ANSI控制台输出。或者,你也可以通过在application.properties文件中设置一个属性值来禁用它。

spring.output.ansi.enabled=NEVER

More information on the configuration of your application logs may be found here.

关于应用程序日志配置的更多信息可以在这里找到。

6. JPA Query Name Checks

6.JPA查询名称检查

At times implementing a data access layer may be a cumbersome activity. A lot of boilerplate code may have to be written to realize simple queries and perform pagination. Spring Data JPA (JPA) aims to significantly facilitate such an implementation of data access layers. This section illustrates some of the benefits of using JPA in conjunction with STS.

有时,实现一个数据访问层可能是一个麻烦的活动。可能需要编写大量的模板代码来实现简单的查询和执行分页。Spring Data JPA (JPA)旨在大大促进数据访问层的实施。本节说明了将JPA与STS结合使用的一些好处。

To get started, add the following dependency for JPA to the previously generated pom.xml:

为了开始工作,请在先前生成的pom.xml中添加以下JPA的依赖关系。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

You may have noticed that version has not been specified in the above declaration. This is due to the fact that dependencies are managed by the spring-boot-starter-parent.

你可能已经注意到,在上述声明中没有指定version。这是由于依赖关系是由spring-boot-starter-parent管理的。

To make JPA work, it is required that you properly define your entity managers and transaction managers. However, Spring auto-configures these for you. The only thing left to the developer is to create the actual entity classes. These entities are managed by the entity manager, which in turn is created by the container. Let us for example create an entity class Foo like so:

为了使JPA工作,需要你正确定义你的实体管理器和事务管理器。然而,Spring会自动为你配置这些。留给开发者的唯一事情就是创建实际的实体类。这些实体是由实体管理器管理的,而实体管理器又是由容器创建的。例如,让我们这样创建一个实体类Foo

@Entity
public class Foo implements Serializable {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;

    // Standard getters and setters
}

The container scans all classes annotated with @Entity from the root of the configuration package. Next we create a JPA repository for the Foo entity:

容器从配置包的根部扫描了所有用@Entity注释的类。接下来我们为Foo实体创建一个JPA资源库。

public interface FooRepository extends JpaRepository<Foo, Integer> {
    public Foo findByNames(String name);
}

At this point you may have noticed already that the IDE now flags this query method with an exception:

在这一点上,你可能已经注意到,IDE现在对这个查询方法标记了一个异常。

Invalid derived query! No property names found for type Foo!

This is of course due to the fact that we have accidentally written an ‘s’ in the method name of the JPA repository. To fix this remove the spurious ‘s’ like so:

这当然是由于我们不小心在JPA存储库的方法名称中写了一个’s’。为了解决这个问题,我们要把这个虚假的’s’去掉,像这样。

public Foo findByName(String name);

Notice that no @EnableJpaRepositories was used on the config class. This is because the container’s AutoConfigration pre-registers one for the project.

请注意,配置类上没有使用 @EnableJpaRepositories。这是因为容器的AutoConfigration为项目预先注册了一个。

7. Jar Type Search

7.罐子类型搜索

“Jar Type Search” is a feature that was introduced in STS 3.5.0. It provides content-assisted proposals in projects for classes that are not (yet) on the classpath. STS may help you adding dependencies to your POM file in case they are not yet on the classpath.

“Jar Type Search “是在STS 3.5.0中引入的一项功能。它在项目中为(尚未)在classpath上的类提供了内容辅助建议。STS可以帮助您在POM文件中添加依赖项,以防它们尚未在classpath中。

For example, let us add a line to the Foo entity class. For this example to work properly, please ensure first that the import statement for java.util.List is already present. Now we may add Google Guava as follows:

例如,让我们给Foo实体类添加一行。为了使这个例子正常工作,请首先确保 java.util.List的导入语句已经存在。现在我们可以添加Google Guava,如下所示。

private List<String> strings = Lists // ctrl + SPACE to get code completion

The IDE will suggest several dependencies to be added to the classpath. Add the dependency from com.google.common.collect, press return and add the dependency from Guava. The Guava jar will now automatically be added to your pom.xml file like so:

IDE会建议在classpath中添加几个依赖项。添加来自com.google.common.collect的依赖,按返回键,添加来自Guava的依赖。现在Guava jar将自动被添加到你的pom.xml文件中,像这样。

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

As of version STS 3.8.0, you get a confirmation dialog box before STS makes its changes to your pom.xml.

STS 3.8.0版本开始,在STS对您的pom.xml.进行更改之前,您会收到一个确认对话框。

8. Adding Application Arguments

8.添加应用参数

One of the other powerful features of Spring is the support of external configurations which can be passed to an application in several ways, e.g. as command-line arguments, specified in properties or YAML files or as system properties. In this section, we focus on adding a configuration option as application start argument using STS. This is illustrated by configuring Tomcat to start on a different port.

Spring的另一个强大功能是对外部配置的支持,这些配置可以通过多种方式传递给应用程序,例如作为命令行参数、在属性或YAML文件中指定或作为系统属性。在本节中,我们将重点讨论如何使用STS将配置选项作为应用程序的启动参数。这将通过配置Tomcat在不同的端口启动来说明。

In order to run an application on a Tomcat port other than the default, you may use the command below, where a custom port is specified as command-line argument:

为了在Tomcat端口以外的地方运行一个应用程序,你可以使用下面的命令,其中一个自定义端口被指定为命令行参数。

mvn spring-boot:run -Drun.arguments="--server.port=7070"

When using STS, you have go to the run menu. Select run configurations… from the Run Configurations dialog, select Spring Boot App from the left panel and select demo – DemoApplication (this will be different if you did not select the default project). From (x)= Arguments tab type in the Program Arguments window

使用STS时,你必须进入run菜单。从 “运行配置 “对话框中选择运行配置…,从左边面板选择Spring Boot App,然后选择demo – DemoApplication(如果你没有选择默认项目,这将是不同的)。从(x)= Arguments标签在Program Arguments窗口中输入

--server.port=7070

and run. You should see output in your console similar to the output that is shown below:

运行。你应该在你的控制台看到与下面显示的输出相似的输出。

.
.
2016-07-06 13:51:40.999  INFO 8724 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 7070 (http)
2016-07-06 13:51:41.006  INFO 8724 --- [           main] com.baeldung.boot.DemoApplication        : Started DemoApplication in 6.245 seconds (JVM running for 7.34)

9. Conclusion

9.结论

In this article we have shown the basics of developing a Spring project in STS. Some of the things we have shown are execution of applications in STS, support during the development of Spring Data JPA and the usage of command-line arguments. However, there are many more useful features that may be employed during development as STS offers a rich set of features.

在这篇文章中,我们展示了在STS中开发Spring项目的基础知识。我们已经展示了一些东西,包括在STS中执行应用程序,在开发Spring Data JPA期间的支持,以及命令行参数的使用。然而,由于STS提供了丰富的功能,在开发过程中还有许多有用的功能可以使用。

The full implementation of this article can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.

本文的完整实现可以在github项目中找到 – 这是一个基于Eclipse的项目,所以应该很容易导入并按原样运行。