一、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封装读取配置文件的类。前面在SrpingBoot源码解析(一)里已经说过,springboot的启动是通过SpringApplication.run方法启动,读取配置。那么读取配置的是哪个类呢。是这个ConfigurableApplicationContext。
下面是它的源码,它是一个接口,从接口方法中可以看出ConfigurableApplicationContext本身可以启动getApplicationStartup ,然后读取一些环境变量信息ConfigurableEnvironment getEnvironment(); 它本身也是一个bean,通过类加载器进行初始化, void setClassLoader(ClassLoader classLoader); 创建出bean。 ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException; 从源码中可以看出ConfigurableApplicationContext,具有监听上下文配置信息变化的功能。
void addApplicationListener(ApplicationListener<?> listener);
和生命周期管理功能 Lifecycle
/*
* 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.context;
import java.io.Closeable;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ProtocolResolver;
import org.springframework.core.metrics.ApplicationStartup;
import org.springframework.lang.Nullable;
/**
* SPI interface to be implemented by most if not all application contexts.
* Provides facilities to configure an application context in addition
* to the application context client methods in the
* {@link org.springframework.context.ApplicationContext} interface.
*
* <p>Configuration and lifecycle methods are encapsulated here to avoid
* making them obvious to ApplicationContext client code. The present
* methods should only be used by startup and shutdown code.
*
* @author Juergen Hoeller
* @author Chris Beams
* @author Sam Brannen
* @since 03.11.2003
*/
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
/**
* Any number of these characters are considered delimiters between
* multiple context config paths in a single String value.
* @see org.springframework.context.support.AbstractXmlApplicationContext#setConfigLocation
* @see org.springframework.web.context.ContextLoader#CONFIG_LOCATION_PARAM
* @see org.springframework.web.servlet.FrameworkServlet#setContextConfigLocation
*/
String CONFIG_LOCATION_DELIMITERS = ",; \t\n";
/**
* Name of the ConversionService bean in the factory.
* If none is supplied, default conversion rules apply.
* @since 3.0
* @see org.springframework.core.convert.ConversionService
*/
String CONVERSION_SERVICE_BEAN_NAME = "conversionService";
/**
* Name of the LoadTimeWeaver bean in the factory. If such a bean is supplied,
* the context will use a temporary ClassLoader for type matching, in order
* to allow the LoadTimeWeaver to process all actual bean classes.
* @since 2.5
* @see org.springframework.instrument.classloading.LoadTimeWeaver
*/
String LOAD_TIME_WEAVER_BEAN_NAME = "loadTimeWeaver";
/**
* Name of the {@link Environment} bean in the factory.
* @since 3.1
*/
String ENVIRONMENT_BEAN_NAME = "environment";
/**
* Name of the System properties bean in the factory.
* @see java.lang.System#getProperties()
*/
String SYSTEM_PROPERTIES_BEAN_NAME = "systemProperties";
/**
* Name of the System environment bean in the factory.
* @see java.lang.System#getenv()
*/
String SYSTEM_ENVIRONMENT_BEAN_NAME = "systemEnvironment";
/**
* Name of the {@link ApplicationStartup} bean in the factory.
* @since 5.3
*/
String APPLICATION_STARTUP_BEAN_NAME = "applicationStartup";
/**
* {@link Thread#getName() Name} of the {@linkplain #registerShutdownHook()
* shutdown hook} thread: {@value}.
* @since 5.2
* @see #registerShutdownHook()
*/
String SHUTDOWN_HOOK_THREAD_NAME = "SpringContextShutdownHook";
/**
* Set the unique id of this application context.
* @since 3.0
*/
void setId(String id);
/**
* Set the parent of this application context.
* <p>Note that the parent shouldn't be changed: It should only be set outside
* a constructor if it isn't available when an object of this class is created,
* for example in case of WebApplicationContext setup.
* @param parent the parent context
* @see org.springframework.web.context.ConfigurableWebApplicationContext
*/
void setParent(@Nullable ApplicationContext parent);
/**
* Set the {@code Environment} for this application context.
* @param environment the new environment
* @since 3.1
*/
void setEnvironment(ConfigurableEnvironment environment);
/**
* Return the {@code Environment} for this application context in configurable
* form, allowing for further customization.
* @since 3.1
*/
@Override
ConfigurableEnvironment getEnvironment();
/**
* Set the {@link ApplicationStartup} for this application context.
* <p>This allows the application context to record metrics
* during startup.
* @param applicationStartup the new context event factory
* @since 5.3
*/
void setApplicationStartup(ApplicationStartup applicationStartup);
/**
* Return the {@link ApplicationStartup} for this application context.
* @since 5.3
*/
ApplicationStartup getApplicationStartup();
/**
* Add a new BeanFactoryPostProcessor that will get applied to the internal
* bean factory of this application context on refresh, before any of the
* bean definitions get evaluated. To be invoked during context configuration.
* @param postProcessor the factory processor to register
*/
void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor);
/**
* Add a new ApplicationListener that will be notified on context events
* such as context refresh and context shutdown.
* <p>Note that any ApplicationListener registered here will be applied
* on refresh if the context is not active yet, or on the fly with the
* current event multicaster in case of a context that is already active.
* @param listener the ApplicationListener to register
* @see org.springframework.context.event.ContextRefreshedEvent
* @see org.springframework.context.event.ContextClosedEvent
*/
void addApplicationListener(ApplicationListener<?> listener);
/**
* Specify the ClassLoader to load class path resources and bean classes with.
* <p>This context class loader will be passed to the internal bean factory.
* @since 5.2.7
* @see org.springframework.core.io.DefaultResourceLoader#DefaultResourceLoader(ClassLoader)
* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#setBeanClassLoader
*/
void setClassLoader(ClassLoader classLoader);
/**
* Register the given protocol resolver with this application context,
* allowing for additional resource protocols to be handled.
* <p>Any such resolver will be invoked ahead of this context's standard
* resolution rules. It may therefore also override any default rules.
* @since 4.3
*/
void addProtocolResolver(ProtocolResolver resolver);
/**
* Load or refresh the persistent representation of the configuration, which
* might be from Java-based configuration, an XML file, a properties file, a
* relational database schema, or some other format.
* <p>As this is a startup method, it should destroy already created singletons
* if it fails, to avoid dangling resources. In other words, after invocation
* of this method, either all or no singletons at all should be instantiated.
* @throws BeansException if the bean factory could not be initialized
* @throws IllegalStateException if already initialized and multiple refresh
* attempts are not supported
*/
void refresh() throws BeansException, IllegalStateException;
/**
* Register a shutdown hook with the JVM runtime, closing this context
* on JVM shutdown unless it has already been closed at that time.
* <p>This method can be called multiple times. Only one shutdown hook
* (at max) will be registered for each context instance.
* <p>As of Spring Framework 5.2, the {@linkplain Thread#getName() name} of
* the shutdown hook thread should be {@link #SHUTDOWN_HOOK_THREAD_NAME}.
* @see java.lang.Runtime#addShutdownHook
* @see #close()
*/
void registerShutdownHook();
/**
* Close this application context, releasing all resources and locks that the
* implementation might hold. This includes destroying all cached singleton beans.
* <p>Note: Does <i>not</i> invoke {@code close} on a parent context;
* parent contexts have their own, independent lifecycle.
* <p>This method can be called multiple times without side effects: Subsequent
* {@code close} calls on an already closed context will be ignored.
*/
@Override
void close();
/**
* Determine whether this application context is active, that is,
* whether it has been refreshed at least once and has not been closed yet.
* @return whether the context is still active
* @see #refresh()
* @see #close()
* @see #getBeanFactory()
*/
boolean isActive();
/**
* Return the internal bean factory of this application context.
* Can be used to access specific functionality of the underlying factory.
* <p>Note: Do not use this to post-process the bean factory; singletons
* will already have been instantiated before. Use a BeanFactoryPostProcessor
* to intercept the BeanFactory setup process before beans get touched.
* <p>Generally, this internal factory will only be accessible while the context
* is active, that is, in-between {@link #refresh()} and {@link #close()}.
* The {@link #isActive()} flag can be used to check whether the context
* is in an appropriate state.
* @return the underlying bean factory
* @throws IllegalStateException if the context does not hold an internal
* bean factory (usually if {@link #refresh()} hasn't been called yet or
* if {@link #close()} has already been called)
* @see #isActive()
* @see #refresh()
* @see #close()
* @see #addBeanFactoryPostProcessor
*/
ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
}