一、Spring Boot概述
Spring Boot是由Pivotal团队开发的一个开源框架,其目标是简化Spring应用的初始化和开发过程。它提供了一种快速构建独立、可运行的、生产级别的Spring应用程序的方式。Spring Boot使用了约定优于配置的原则,大部分的配置都是默认的,这大大减少了开发人员的工作量。
二、Spring Boot的特点
- 独立运行:Spring Boot可以打包成一个可执行的JAR文件,不需要依赖Tomcat或其他Servlet容器就可以独立运行。
- 自动配置:Spring Boot能自动配置大部分常用的设置,开发人员不需要手动配置。
- 简化Maven配置:Spring Boot提供了starter POMs,可以简化Maven的依赖配置。
- 嵌入式Servlet容器:Spring Boot内嵌了Tomcat、Jetty等Servlet容器,简化了部署。
- 简化Spring开发:通过自动配置和约定大于配置的原则,简化了Spring应用的开发过程。
- 集成了大量常用的第三方库:Spring Boot集成了大量常用的第三方库,如H2数据库、Thymeleaf模板引擎等。
- 提供了生产就绪功能:例如健康检查和外部化配置,使应用更好地适应生产环境。
- 强大的社区支持:Spring Boot有庞大的开发者社区,为开发者提供了丰富的资源和支持。
三、如何使用Spring Boot
- 创建项目:使用Spring Initializr创建一个新的Spring Boot项目。也可以选择使用构建工具如Maven或Gradle。
- 定义应用程序的主类:创建一个主类,并使用
@SpringBootApplication
注解标记它。这个注解是一个复合注解,它包括了@Configuration
、@EnableAutoConfiguration
和@ComponentScan
。 - 编写业务代码:在主类中定义一个或多个Controller类,用于处理HTTP请求和响应。在Controller类中编写业务逻辑,并使用Model类传递数据。
- 配置文件:在
src/main/resources
目录下创建或修改application.properties
或application.yml
文件,用于配置应用程序的参数。 - 运行应用程序:使用命令行运行应用程序。如果使用Maven,可以在命令行中输入
mvn spring-boot:run
;如果使用Gradle,可以在命令行中输入gradle bootRun
。 - 测试应用程序:使用JUnit对应用程序进行单元测试和集成测试。Spring Boot集成了JUnit,可以方便地编写和运行测试用例。
- 打包部署:如果需要将应用程序部署到生产环境,可以使用Spring Boot的打包功能将应用程序打包成一个可执行的JAR文件或WAR文件,然后将其部署到服务器上。
四、最佳实践
- 遵循单一职责原则:每个类和组件都应该有单一的职责,避免出现职责过多的类或组件。这可以提高代码的可维护性和可读性。
- 使用Lombok减少代码量:Lombok是一个Java库,可以减少模板代码的编写量。通过在类中添加Lombok注解,可以自动生成一些常用的方法,如getters和setters等。
- 利用Spring Data JPA简化数据库操作:Spring Data JPA是一个简化数据库操作的框架,通过简单的注解和接口定义就可以实现数据库操作。它能够大大提高开发效率。
- 利用Spring Cloud提高可扩展性:Spring Cloud是一套基于Spring Boot的微服务开发框架,它提供了服务注册与发现、负载均衡、熔断机制等功能,可以提高应用程序的可扩展性和可靠性。
- 遵循RESTful原则设计API:RESTful是一种设计API的风格,它强调使用HTTP协议的方法(如GET、POST、PUT、DELETE等)来进行资源的操作。遵循RESTful原则可以提高API的可读性和可维护性。
- 使用AOP(面向切面编程)进行日志和安全控制:AOP是一种编程范式,它允许程序员定义“切面”,用于在程序的特定点(如方法调用之前或之后)执行特定的代码。这可以用于实现日志记录、安全控制等功能。
- 利用Docker进行容器化部署:Docker是一种容器化技术,它可以让应用程序与其依赖项一起打包并部署到任何地方。通过使用Docker,可以简化部署过程并提高应用程序的可移植性。
- 利用性能监控和度量数据进行优化:性能监控和度量是任何应用程序的重要部分。通过收集和分析这些数据,开发人员可以找出性能瓶颈并进行优化。一些工具如Prometheus和Grafana可以帮助实现这一目标。
- 利用Spring Security进行安全控制
前面一到八已经赏析完springboot的最基础组件功能,作为web项目,而不单单是java项目,不能只停留在IOC和AOP。web项目是可以通过浏览器URL访问的项目。那SpringBoot里是如何支持的能。现在就来说说应用层面的源码和最接近开发者的东西。
org.springframework.web
Spring-web定义了SpringBoot的web的基本框架,请求响应瀑布流。也就是我们只需要写controller就能处理接收来自网络的http请求。进而访问到service和dao层的逻辑。
先赏析web包的基本结构
从源码中可以看出web包给出了http协议访问的支持。
1.现在看一下对Controller的支持,通过注解的方式对Controller进行支持。
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Controller;
/**
* A convenience annotation that is itself annotated with
* {@link Controller @Controller} and {@link ResponseBody @ResponseBody}.
* <p>
* Types that carry this annotation are treated as controllers where
* {@link RequestMapping @RequestMapping} methods assume
* {@link ResponseBody @ResponseBody} semantics by default.
*
* <p><b>NOTE:</b> {@code @RestController} is processed if an appropriate
* {@code HandlerMapping}-{@code HandlerAdapter} pair is configured such as the
* {@code RequestMappingHandlerMapping}-{@code RequestMappingHandlerAdapter}
* pair which are the default in the MVC Java config and the MVC namespace.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 4.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
/**
* 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 (or empty String otherwise)
* @since 4.0.1
*/
@AliasFor(annotation = Controller.class)
String value() default "";
}
2.对客户端请求方法的支持
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
/**
* Annotation for mapping web requests onto methods in request-handling classes
* with flexible method signatures.
*
* <p>Both Spring MVC and Spring WebFlux support this annotation through a
* {@code RequestMappingHandlerMapping} and {@code RequestMappingHandlerAdapter}
* in their respective modules and package structure. For the exact list of
* supported handler method arguments and return types in each, please use the
* reference documentation links below:
* <ul>
* <li>Spring MVC
* <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-arguments">Method Arguments</a>
* and
* <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-return-types">Return Values</a>
* </li>
* <li>Spring WebFlux
* <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-ann-arguments">Method Arguments</a>
* and
* <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-ann-return-types">Return Values</a>
* </li>
* </ul>
*
* <p><strong>Note:</strong> This annotation can be used both at the class and
* at the method level. In most cases, at the method level applications will
* prefer to use one of the HTTP method specific variants
* {@link GetMapping @GetMapping}, {@link PostMapping @PostMapping},
* {@link PutMapping @PutMapping}, {@link DeleteMapping @DeleteMapping}, or
* {@link PatchMapping @PatchMapping}.</p>
*
* <p><b>NOTE:</b> When using controller interfaces (e.g. for AOP proxying),
* make sure to consistently put <i>all</i> your mapping annotations - such as
* {@code @RequestMapping} and {@code @SessionAttributes} - on
* the controller <i>interface</i> rather than on the implementation class.
*
* @author Juergen Hoeller
* @author Arjen Poutsma
* @author Sam Brannen
* @since 2.5
* @see GetMapping
* @see PostMapping
* @see PutMapping
* @see DeleteMapping
* @see PatchMapping
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
/**
* Assign a name to this mapping.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used on both levels, a combined name is derived by concatenation
* with "#" as separator.
* @see org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder
* @see org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy
*/
String name() default "";
/**
* The primary mapping expressed by this annotation.
* <p>This is an alias for {@link #path}. For example,
* {@code @RequestMapping("/foo")} is equivalent to
* {@code @RequestMapping(path="/foo")}.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit
* this primary mapping, narrowing it for a specific handler method.
* <p><strong>NOTE</strong>: A handler method that is not mapped to any path
* explicitly is effectively mapped to an empty path.
*/
@AliasFor("path")
String[] value() default {};
/**
* The path mapping URIs (e.g. {@code "/profile"}).
* <p>Ant-style path patterns are also supported (e.g. {@code "/profile/**"}).
* At the method level, relative paths (e.g. {@code "edit"}) are supported
* within the primary mapping expressed at the type level.
* Path mapping URIs may contain placeholders (e.g. <code>"/${profile_path}"</code>).
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit
* this primary mapping, narrowing it for a specific handler method.
* <p><strong>NOTE</strong>: A handler method that is not mapped to any path
* explicitly is effectively mapped to an empty path.
* @since 4.2
*/
@AliasFor("value")
String[] path() default {};
/**
* The HTTP request methods to map to, narrowing the primary mapping:
* GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit this
* HTTP method restriction.
*/
RequestMethod[] method() default {};
/**
* The parameters of the mapped request, narrowing the primary mapping.
* <p>Same format for any environment: a sequence of "myParam=myValue" style
* expressions, with a request only mapped if each such parameter is found
* to have the given value. Expressions can be negated by using the "!=" operator,
* as in "myParam!=myValue". "myParam" style expressions are also supported,
* with such parameters having to be present in the request (allowed to have
* any value). Finally, "!myParam" style expressions indicate that the
* specified parameter is <i>not</i> supposed to be present in the request.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit this
* parameter restriction.
*/
String[] params() default {};
/**
* The headers of the mapped request, narrowing the primary mapping.
* <p>Same format for any environment: a sequence of "My-Header=myValue" style
* expressions, with a request only mapped if each such header is found
* to have the given value. Expressions can be negated by using the "!=" operator,
* as in "My-Header!=myValue". "My-Header" style expressions are also supported,
* with such headers having to be present in the request (allowed to have
* any value). Finally, "!My-Header" style expressions indicate that the
* specified header is <i>not</i> supposed to be present in the request.
* <p>Also supports media type wildcards (*), for headers such as Accept
* and Content-Type. For instance,
* <pre class="code">
* @RequestMapping(value = "/something", headers = "content-type=text/*")
* </pre>
* will match requests with a Content-Type of "text/html", "text/plain", etc.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit this
* header restriction.
* @see org.springframework.http.MediaType
*/
String[] headers() default {};
/**
* Narrows the primary mapping by media types that can be consumed by the
* mapped handler. Consists of one or more media types one of which must
* match to the request {@code Content-Type} header. Examples:
* <pre class="code">
* consumes = "text/plain"
* consumes = {"text/plain", "application/*"}
* consumes = MediaType.TEXT_PLAIN_VALUE
* </pre>
* Expressions can be negated by using the "!" operator, as in
* "!text/plain", which matches all requests with a {@code Content-Type}
* other than "text/plain".
* <p><b>Supported at the type level as well as at the method level!</b>
* If specified at both levels, the method level consumes condition overrides
* the type level condition.
* @see org.springframework.http.MediaType
* @see javax.servlet.http.HttpServletRequest#getContentType()
*/
String[] consumes() default {};
/**
* Narrows the primary mapping by media types that can be produced by the
* mapped handler. Consists of one or more media types one of which must
* be chosen via content negotiation against the "acceptable" media types
* of the request. Typically those are extracted from the {@code "Accept"}
* header but may be derived from query parameters, or other. Examples:
* <pre class="code">
* produces = "text/plain"
* produces = {"text/plain", "application/*"}
* produces = MediaType.TEXT_PLAIN_VALUE
* produces = "text/plain;charset=UTF-8"
* </pre>
* <p>If a declared media type contains a parameter (e.g. "charset=UTF-8",
* "type=feed", "type=entry") and if a compatible media type from the request
* has that parameter too, then the parameter values must match. Otherwise
* if the media type from the request does not contain the parameter, it is
* assumed the client accepts any value.
* <p>Expressions can be negated by using the "!" operator, as in "!text/plain",
* which matches all requests with a {@code Accept} other than "text/plain".
* <p><b>Supported at the type level as well as at the method level!</b>
* If specified at both levels, the method level produces condition overrides
* the type level condition.
* @see org.springframework.http.MediaType
*/
String[] produces() default {};
}