hj_springboot
官方文档 springboot
一: 基本使用-->
springboot 简化了spring应用的初始搭建及开发过程.该框架通过众多的启动器,约定大于配置.
整合其他的第三方jar包,从而简化便捷开发工作,使开发人员能够更加专注于业务逻辑的梳理编码.
可以直接访问 https://start.spring.io/ 初始化maven project ;
pom文件中 默认有以下两个模块:
spring-boot-starter: 核心模块,包括自动配置支持,日志,yaml等;
spring-boot-stater-test: 测试模块;
引入web模块,即可写对外访问接口 <这个模块有内置spring-boot-starter依赖>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 热更新 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${springboot.version}</version> <!-- 如果没有该配置,devtools 可能不会生效 --> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build>
编写 controller ,@RestController 是@Controller与@ResponseBody的结合体.里面的方法都以json格式返回;
@RestController public class HelloWorldController { @RequestMapping("/hj") public String index() { return "hj_独孤华剑"; } }
可以使用 MockMvc 进行接口测试.示例:
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @SpringBootTest public class HjTest01 { private MockMvc mvc; // junit5 的写法. junit4 是@Before @BeforeEach public void setUp() { mvc = MockMvcBuilders.standaloneSetup(new TestController()).build(); } @Test public void getHello() throws Exception { ResultActions resultActions = this.mvc.perform( MockMvcRequestBuilders.get("/test/hj") .accept(MediaType.APPLICATION_JSON) ); // 解决控制台打印 body 中文乱码 resultActions.andReturn().getResponse().setCharacterEncoding("UTF-8"); //添加断言 resultActions.andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.status().isOk()); } }
常用的注解:
@SpringBootApplication @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan
@RestController @RequestBody @RequestMapping @PathVariable @RequestParam
@Component @Repository @Service @Scope @Entity @Bean @Resource
@PropertySource @ImportResource @Import @Configuration @Transactional
@ControllerAdvice @ExceptionHandler @SpringBootTest @RunWith @BeforEach...
常用的组件启动器:
Name | Description |
---|---|
Core starter, including auto-configuration support, logging and YAML *stater* |
|
Starter for JMS messaging using Apache ActiveMQ *activemq* |
|
Starter for using Spring AMQP and Rabbit MQ *rabbitmq* |
|
Starter for aspect-oriented programming with Spring AOP and AspectJ *aop* |
|
Starter for JMS messaging using Apache Artemis |
|
Starter for using Spring Batch *batch* |
|
Starter for using Spring Framework’s caching support *catch* |
|
Starter for using Cassandra distributed database and Spring Data Cassandra |
|
Starter for using Cassandra distributed database and Spring Data Cassandra Reactive |
|
Starter for using Couchbase document-oriented database and Spring Data Couchbase |
|
Starter for using Couchbase document-oriented database and Spring Data Couchbase Reactive |
|
Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch *elasticsearch* |
|
Starter for using Spring Data JDBC *jdbc* |
|
Starter for using Spring Data JPA with Hibernate *jpa* |
|
Starter for using Spring Data LDAP |
|
Starter for using MongoDB document-oriented database and Spring Data MongoDB *mongodb* |
|
Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive |
|
Starter for using Neo4j graph database and Spring Data Neo4j |
|
Starter for using Spring Data R2DBC |
|
Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client *redis* |
|
Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client |
|
Starter for exposing Spring Data repositories over REST using Spring Data REST |
|
Starter for building MVC web applications using FreeMarker views *freemarker* |
|
Starter for building MVC web applications using Groovy Templates views |
|
Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS |
|
Starter for using Spring Integration |
|
Starter for using JDBC with the HikariCP connection pool *jdbc* |
|
Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to |
|
Starter for using jOOQ to access SQL databases. An alternative to |
|
Starter for reading and writing json *json* |
|
Starter for JTA transactions using Atomikos |
|
Starter for using Java Mail and Spring Framework’s email sending support *mail* |
|
Starter for building web applications using Mustache views |
|
Starter for using Spring Security’s OAuth2/OpenID Connect client features *oauth2* |
|
Starter for using Spring Security’s OAuth2 resource server features *oauth2* |
|
Starter for using the Quartz scheduler |
|
Starter for building RSocket clients and servers |
|
Starter for using Spring Security *security* |
|
Starter for testing Spring Boot applications with libraries including JUnit Jupiter, Hamcrest and Mockito *test* |
|
Starter for building MVC web applications using Thymeleaf views *thymeleaf* |
|
Starter for using Java Bean Validation with Hibernate Validator *validation* |
|
Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container *web* |
|
Starter for using Spring Web Services |
|
Starter for building WebFlux applications using Spring Framework’s Reactive Web support |
|
Starter for building WebSocket applications using Spring Framework’s WebSocket support *websocket* |
springboot 的启动流程:
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>(); configureHeadlessProperty(); //1.通过SpringFactoriesLoader查找加载所有的SpringApplicationRunListeners,通过调用starting()方法通知所有的SpringApplicationRunListeners:应用开始启动了 SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); try { //2.创建并配置Environment ApplicationArguments applicationArguments = new DefaultApplicationArguments( args); ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); configureIgnoreBeanInfo(environment); //3.打印banner Banner printedBanner = printBanner(environment); //4.根据是否是web项目,来创建不同的ApplicationContext容器 context = createApplicationContext(); //5.创建一系列FailureAnalyzer exceptionReporters = getSpringFactoriesInstances( SpringBootExceptionReporter.class, new Class[] { ConfigurableApplicationContext.class }, context); //6.初始化ApplicationContext prepareContext(context, environment, listeners, applicationArguments, printedBanner); //7.调用ApplicationContext的refresh()方法,刷新容器 refreshContext(context); //8.查找当前context中是否注册有CommandLineRunner和ApplicationRunner,如果有则遍历执行它们。 afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass) .logStarted(getApplicationLog(), stopWatch); } listeners.started(context); callRunners(context, applicationArguments); } catch (Throwable ex) { handleRunFailure(context, listeners, exceptionReporters, ex); throw new IllegalStateException(ex); } listeners.running(context); return context; }
@Configuration @ComponentScan @EnableAutoConfiguration ==>>
@SpringBootApplication-->SpringApplication.run(HJ.class,args)