Spring Boot 入门笔记

这篇博客介绍了Spring Boot入门,包括依赖管理、最佳实践、运行应用、禁用Thymeleaf缓存、代码结构建议、配置类、自动配置和开发者工具的使用。强调了Spring Boot与特定Spring版本的关联,以及如何通过Maven或Gradle创建可执行jar。

Spring Boot 入门

  • Build systems: Maven | Gradle | Ant | Starter POMs
  • Best practices: Code Structure | @Configuration | @EnableAutoConfiguration | Beans and Dependency Injection
  • Running your code: IDE | Packaged | Maven| Gradle
  • Package your app: Production jars
  • Spring Boot CLI: Using the CLI

Tips:

Spring Boot use Java SDK v1.6 or higher, running in Tomcat 7.0 or higher.
Maven compile sources from src/main/java folder by defaule.
SpringApplication will bootstrap our application, starting Spring which will in turn start the auto-configured Tomcat web server.
Executable jars (sometimes called “fat jars”) are archives containing your compiled classes along with all of the jar dependencies that your code needs to run.
project.version.SNAPSHOT.jar.original is the original jar file that Maven created before it was repackaged by Sping Boot.
To create an executable jar we need to add the spring-boot-maven-plugin to our pom.xml.
Each release of Spring Boot is associated with a base version of the Spring Framework so we highly recommend you to not specify its version on your own.
Spring Boot dependencies: https://github.com/spring-projects/spring-boot/blob/v1.3.6.RELEASE/spring-boot-dependencies/pom.xml
Spring Boot Starter reference: https://github.com/spring-projects/spring-boot/blob/master/spring-boot-starters/README.adoc

Annotation Definations:

Stereotype Annotation: Provides hints for people reading the code, and for Spring, that the class plays a specific role.

AnnotationDefination
@ControllerSpring will consider this class when handling incoming web requests.
@RestControllerTells Spring to render the resulting string directly back to the caller(kind of @Controller).
@RequestMappingProvides “routing” information: telling Spring how to map HTTP Request Path to method.
@EnableAutoConfigurationA class-level annotation: telling Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that your have added.
@ComponentScanUse this annotation to find your beans.
@AutowiredConstruct injection.
@ServiceConstruct injection.
@RepositoryConstruct injection.
@ComponentConstruct injection.

Use @ComponentScan to find beans.

All of application components will be automatically registered as Spring Beans:
@Component @Service @Repository @Controller

Main class annotation

@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan

package com.example.myproject;

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);
    }

}

Running application:

executable jar: java -jar target/myproject-0.0.1-SNAPSHOT.jar
Maven: mvn spring-boot:run
Gradle: gradle bootRun

Disable thymeleaf cache:

config settings in application.properties:spring.thymeleaf.cache:false

Structuring your code(Best Practices):

1. Do not use the “default package”:

When a class doesn’t include a package declaration it is considered to be in the “default package”. The use of the “default package” is generally discouraged, and should be avoided. It can cause particular problems for Spring Boot applications that use @ComponentScan, @EntityScan or @SpringBootApplication annotations, since every class from every jar, will be read.

2. Locating the main application class:

We generally recommend that you locate your main application class in a root package above other classes. Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute. You can also use the @SpringBootApplication annotation if your main class is in the root package.
Here is a typical layout:

com
 +- example
     +- myproject
         +- Application.java
         |
         +- domain
         |   +- Customer.java
         |   +- CustomerRepository.java
         |
         +- service
         |   +- CustomerService.java
         |
         +- web
             +- CustomerController.java

Configuration classes:

Spring Boot favors Java-based configuration.

1. Importing additional cofiguration classes:

You don’t need to put all your @Configuration into a single class. The @Import annotation can be used to import additional configuration classes. Alternatively, you can use @ComponentScan to automatically pick up all Spring components, including @Configuration classes.

2. Importing XML configuration:

If you absolutely must use XML based configuration, we recommend that you still start with a @Configuration class. You can then use an additional @ImportResource annotation to load XML configuration files.

Auto-configuration:

Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration or @SpringBootApplication annotations to one of your @Configuration classes.

1. Gradually replacing auto-configuration

Auto-configuration is noninvasive, at any point you can start to define your own configuration to replace specific parts of the auto-configuration.

2. Disabling specific auto-configuration

If you find that specific auto-configure classes are being applied that you don’t want, you can use the exclude attribute of @EnableAutoConfiguration to disable them.

import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;

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

If the class is not on the classpath, you can use the excludeName attribute of the annotation and specify the fully qualified name instead. Finally, you can also control the list of auto-configuration classes to exclude via the spring.autoconfigure.exclude property.

Developer tools:

The spring-boot-devtools module can be included in any project to provide additional development-time features. To include devtools support, simply add the module dependency to your build:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

If you want to ensure that devtools is never included in a production build, you can use the excludeDevtools build property to completely remove the JAR.

Property defaults:

Several of the libraries supported by Spring Boot use caches to improve performance. For example, Thymeleaf will cache templates to save repeatedly parsing XML source files.
The complete list of the properties that are applied:https://github.com/spring-projects/spring-boot/blob/v1.3.6.RELEASE/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java

Automatic restart:

Applications that use spring-boot-devtools will automatically restart whenever files on the classpath change.
The restart technology provided by Spring Boot works by using two classloaders. Classes that don’t change (for example, those from third-party jars) are loaded into a base classloader. Classes that you’re actively developing are loaded into a restart classloader. When the application is restarted, the restart classloader is thrown away and a new one is created. This approach means that application restarts are typically much faster than “cold starts” since the base classloader is already available and populated.
By default, any open project in your IDE will be loaded using the “restart” classloader, and any regular .jar file will be loaded using the “base” classloader.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值