Chapter 1 Hello, Spring Boot

This chapter is the first chapter of the " Spring Boot Quick Start " series of tutorials. To view all chapters in this series, click here .

content

  • Introduction
  • Source code download
  • Software version
  • Create project
  • Write the HelloService class
  • Write the SpringBoot main program
  • running result
  • Summary note

Introduction

In this chapter I will use Spring Boot to develop a program similar to "Hello, World", we will call it "Hello, Spring Boot". Through this small demo program, Java developers who are completely ignorant of Spring Boot can quickly get started and develop with Spring Boot.

Source code download

The sample code in this chapter is placed on "Code Cloud", and you can download or browse it for free: https://git.oschina.net/terran4j/springboot/tree/master/springboot-hello

Software version

Versions of related software used:

  • Java:  1.8
  • Maven:  3.3.9

The program has been debugged in the above versions and can run normally. Other versions are only for reference.

Create project

We use Eclipse (similar to other IDEs) to create a Maven project, and the content of the pom.xml file is as follows:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>terran4j</groupId>
	<artifactId>springboot-hello</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot-hello</name>
	<url>http://maven.apache.org</url>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
	</parent>

	<properties>
		<java.version>1.8</java.version>
	</properties>

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

</project>

The spring-boot-starter-** project is called the Spring Boot Starter (Starter), which is one of the four artifacts provided by Spring Boot. They can be very convenient for package management, which greatly reduces jar hell or dependency hell. You only need to introduce them in pom.xml without a lot of tedious configuration of jar package dependencies, so as to maximize the Avoid the problem of jar version conflict.

Spring Boot defines a lot of starters. Here is a brief introduction to the two starters that have appeared above:

  1. spring-boot-starter-parent: Define a parent pom, which needs your project's pom to inherit from it, like this:
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
	</parent>

spring-boot-starter-parent contains the following information:

  • Use java6 compilation level
  • Use UTF-8 encoding
  • Provides common testing frameworks (JUnit, Hamcrest, Mockito).
  • The dependency management of a large number of open source jar packages is defined (in fact, it is defined by its parent pom: spring-boot-dependencies), so that these open source jar packages do not need to specify the version number, which will avoid the introduction of jar packages caused by different open source projects. Version conflicts, because Spring Boot solves these compatibility problems for you.
  • Defines the dependency management of many plugins, such as: exec plugin, surefire, Git commit ID, shade, etc.
  1. spring-boot-starter-web: Provides the modules required for web development, including the following information:
  • By default, tomcat is embedded as a web container.
  • Provides Spring MVC framework
  • Provides modules commonly used in other web projects, such as spring-web, jackson-databind, etc.

The directory structure after creating this Maven project is as follows:

image.png

Write the HelloService class

Next, we write a very simple class - HelloService, the code is as follows:

package com.terran4j.springboot.hello;

import org.springframework.stereotype.Component;

@Component
public class HelloService {

	public String hello(String name) {
		return "Hello, " + name + "!";
	}
	
}

This class is very simple. The key is the annotation on the HelloService class: @Component, which declares a Spring Bean. When the Spring container scans the class with this annotation, it will be injected into the Spring container.

Spring Boot recommends using annotations to inject a bean into the Spring container, instead of writing a lot of XML configuration like previous Spring programs. Spring Boot only needs Java code or annotations to complete the configuration of Spring Beans.

The annotations for declaring beans are:

  • @Component: declares a bean, but this bean has no explicit role.
  • @Service: Declare a Bean and use it in the business logic layer (Service layer).
  • @Respository: Declare a Bean for use in the data access layer (DAO layer).
  • @Controller: Declare a Bean to be used in the presentation layer (MVC/Spring MVC). The last three annotations (@Service, @Respository, @Controller) all inherit the @Component annotation, which is essentially the same as @Component. For example, the code of @Service is as follows:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any
	 */
	String value() default "";

}

You can see that there is a @Component annotation on @Service. At present, they have the same function, just to make the code easier to understand, but in subsequent versions of Spring Boot, it is possible to give them different functions.

Write the Spring Boot main program

Next we write a main program to call HelloService, the code is as follows:

package com.terran4j.springboot.hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloApp implements ApplicationRunner {
	
	@Autowired
	private HelloService helloService;
	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		String msg = helloService.hello("Spring Boot");
		System.out.println(msg);
	}

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

}

Let's look at this code first, which declares a HelloService property helloService:

    @Autowired
    private HelloService helloService;

The role of @Autowired is to let helloService refer to the HelloService Bean object in the Spring container. The Spring container is very smart. It will find the Bean that most "matches" the current property for automatic assembly. To be precise, it will automatically assemble according to the following rules: 1. Find the matching Bean according to the type, such as the above is to find the type of HelloService Bean of the class or subclass, OK if it exists and is unique. 2. If it is not unique, look for a bean with the same name in the result set according to the attribute name. For example, the above is to find a bean named helloService. Because the name of the bean is unique, it should be possible to determine whether there is a bean that meets the requirements here.

After the bean is autowired, you can use the bean, as shown in the following code:

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String msg = helloService.hello("Spring Boot");
        System.out.println(msg);
    }

Since this class HelloApp implements ApplicationRunner and overrides the run method, the Spring application will call the run method on startup.

Finally we start the Spring Boot application in the main function like:

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

Note that the first parameter of the SpringApplication.run method is the class object of the startup class. This class must be annotated with @SpringBootApplication when it is declared to indicate that it is a startup class. The @SpringBootApplication annotation is a collection of three annotations @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan, which are defined as follows:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
		@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
    // 此处省略,重点看类上面的三个注解。
}

It will scan under the package where the current startup class is located and its subpackages. Any class that declares the @Component annotation or inherits the @Component annotation (such as @Service, @Respository, @Controller or your own definition) will be scanned. Injected into the Spring container.

running result

Finally, we run the HelloApp program, and the console output is as follows:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.2.RELEASE)

// 中间省略一大段日志信息......

2017-07-31 08:57:33.330  INFO 53416 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-07-31 08:57:33.421  INFO 53416 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
Hello, Spring Boot!
2017-07-31 08:57:33.428  INFO 53416 --- [           main] com.terran4j.springboot.hello.HelloApp   : Started HelloApp in 4.889 seconds (JVM running for 5.356)

"Hello, Spring Boot!" appears on the penultimate line, and the result is as expected. "Tomcat started on port(s): 8080 (http)" appears on the third last line, indicating that the Http Web service is started using the embedded Tomcat, but we have not covered the development of the Web in this chapter. We will An introduction to the development of web services.

Summary note

This article is mainly for beginners to get started and experience the development and operation process of Spring Boot in the shortest time. Starting from the next chapter "Spring Boot MVC", we will take you into the learning of practical skills, so that you can master the basic development skills of Spring Boot.

Click here to view all chapters in this series. (The goal of this series is to help programmers with Java development experience to quickly master the basic skills of using Spring Boot to develop, and feel the minimalist development style and super cool programming experience of Spring Boot.)

In addition, we have a WeChat public account called SpringBoot and Microservices . Interested students, please scan the QR code below and follow it. After following, you can receive the technical dry goods we share regularly!SpringBoot and Microservices - Official Account QR Code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325477167&siteId=291194637