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...

 常用的组件启动器:

NameDescription

spring-boot-starter

Core starter, including auto-configuration support, logging and YAML                                 *stater*

spring-boot-starter-activemq

Starter for JMS messaging using Apache ActiveMQ                                                           *activemq*

spring-boot-starter-amqp

Starter for using Spring AMQP and Rabbit MQ                                                                   *rabbitmq*

spring-boot-starter-aop

Starter for aspect-oriented programming with Spring AOP and AspectJ                                 *aop*

spring-boot-starter-artemis

Starter for JMS messaging using Apache Artemis

spring-boot-starter-batch

Starter for using Spring Batch                                                                                            *batch*

spring-boot-starter-cache

Starter for using Spring Framework’s caching support                                                           *catch*

spring-boot-starter-data-cassandra

Starter for using Cassandra distributed database and Spring Data Cassandra

spring-boot-starter-data-cassandra-reactive

Starter for using Cassandra distributed database and Spring Data Cassandra Reactive

spring-boot-starter-data-couchbase

Starter for using Couchbase document-oriented database and Spring Data Couchbase

spring-boot-starter-data-couchbase-reactive

Starter for using Couchbase document-oriented database and Spring Data Couchbase Reactive

spring-boot-starter-data-elasticsearch

Starter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch               *elasticsearch*

spring-boot-starter-data-jdbc

Starter for using Spring Data JDBC                                                                                              *jdbc*

spring-boot-starter-data-jpa

Starter for using Spring Data JPA with Hibernate                                                                           *jpa*

spring-boot-starter-data-ldap

Starter for using Spring Data LDAP

spring-boot-starter-data-mongodb

Starter for using MongoDB document-oriented database and Spring Data MongoDB                         *mongodb*

spring-boot-starter-data-mongodb-reactive

Starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive

spring-boot-starter-data-neo4j

Starter for using Neo4j graph database and Spring Data Neo4j

spring-boot-starter-data-r2dbc

Starter for using Spring Data R2DBC

spring-boot-starter-data-redis

Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client                   *redis*

spring-boot-starter-data-redis-reactive

Starter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client

spring-boot-starter-data-rest

Starter for exposing Spring Data repositories over REST using Spring Data REST

spring-boot-starter-freemarker

Starter for building MVC web applications using FreeMarker views                                                            *freemarker*

spring-boot-starter-groovy-templates

Starter for building MVC web applications using Groovy Templates views

spring-boot-starter-hateoas

Starter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS

spring-boot-starter-integration

Starter for using Spring Integration

spring-boot-starter-jdbc

Starter for using JDBC with the HikariCP connection pool                                                                            *jdbc*

spring-boot-starter-jersey

Starter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web

spring-boot-starter-jooq

Starter for using jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc

spring-boot-starter-json

Starter for reading and writing json                                                                                                           *json*

spring-boot-starter-jta-atomikos

Starter for JTA transactions using Atomikos

spring-boot-starter-mail

Starter for using Java Mail and Spring Framework’s email sending support                                                    *mail*

spring-boot-starter-mustache

Starter for building web applications using Mustache views

spring-boot-starter-oauth2-client

Starter for using Spring Security’s OAuth2/OpenID Connect client features                                                   *oauth2*

spring-boot-starter-oauth2-resource-server

Starter for using Spring Security’s OAuth2 resource server features                                                              *oauth2*

spring-boot-starter-quartz

Starter for using the Quartz scheduler

spring-boot-starter-rsocket

Starter for building RSocket clients and servers

spring-boot-starter-security

Starter for using Spring Security                                                                                                                  *security*

spring-boot-starter-test

Starter for testing Spring Boot applications with libraries including JUnit Jupiter, Hamcrest and Mockito               *test*

spring-boot-starter-thymeleaf

Starter for building MVC web applications using Thymeleaf views                                                                       *thymeleaf*

spring-boot-starter-validation

Starter for using Java Bean Validation with Hibernate Validator                                                                           *validation*

spring-boot-starter-web

Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container    *web*

spring-boot-starter-web-services

Starter for using Spring Web Services

spring-boot-starter-webflux

Starter for building WebFlux applications using Spring Framework’s Reactive Web support

spring-boot-starter-websocket

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)

 

 

posted @ 2021-10-11 15:38  独孤~华剑  阅读(102)  评论(0编辑  收藏  举报
独孤华剑