SpringBoot入门

SpringBoot入门

约定大于配置

1.启动引导Spring

步骤:

  • 使用SpringInitializr/SpringCli/ide初始化SpringBoot项目其中包含;

    • 使用maven[打包方式jar包]/gradle进行工程搭建;
     maven工程需要继承pom父工程spring-boot-starter-parent且打包方式jar包
     <parent>
     	<groupId>org.springframework.boot</groupId>
     	<artifactId>spring-boot-starter-parent</artifactId>
     	<version>2.0.6.RELEASE</version>
     	<relativePath/> <!-- lookup parent from repository -->
     </parent>
    
    • 指定使用的jdk版本
    <properties>
        <java.version>1.8</java.version>
    </properties>
    
    • 创建启动类,编写main方法并启动;
    SpringBoot要集成SpringMVC进行Controller的开发,所以项目要导入web的启动依赖
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
    • 创建测试类
    • 在resource创建静态资源目录static和模板目录template

    并且

     在resource目录下创建SpringBoot配置文件application.properties 且文件名固定写死
     @SpringBootApplication//开启组件扫描和自动配置 用来修饰启动类
     SpringApplication.run(启动类类名.class,args);//负责启动引导应用程序
    

注意:@SpringBootApplication本质上糅合了以下的注解故而启动类应放在项目目录的最上层

Spring的@Configuration:标明该类使用Spring基于Java的配置;
Spring的@ComponentScan:启用组件扫描,如此组件才能被自动发现并注册为Spring应用程序上下文里的Bean。
SpringBoot的@EnableAutoConfiguration:开启SpirngBoot自动配置

web工程静态资源

静态资源应该放到resources/static目录下,就可以直接访问。
相当于静态资源的根目录。

配置文件

SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用application.properties或者application.yml(application.yaml)进行配置。

配置文件名必须是application

application.properties
    只需要配置一些必要的配置。例如数据的连接串。
    语法:key=value
    示例:
        #DB Configuration:
        spring.datasource.driverClassName=com.mysql.jdbc.Driver
        spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot60?useUnicode=true&characterEncoding=utf8
        spring.datasource.username=root
        spring.datasource.password=root
        
        #JPA Configuration:
        spring.jpa.database=MySQL
        spring.jpa.show-sql=true
        spring.jpa.generate-ddl=true

··

application.yml
    语法:key: value   注意value前有一个空格
    示例:
        #DB Configuration:
        spring:
          datasource:
            driverClassName: com.mysql.jdbc.Driver
            url: jdbc:mysql://127.0.0.1:3306/springboot60?useUnicode=true&characterEncoding=utf8
            username: root
            password: root
        #JPA Configuration:
          jpa:
            database: MySQL
            show-sql: true
            generate-ddl: true
    配置集合:
    语法:
    	key:
        	- value1
        	- value2
        	注意:value1与-之间存在一个空格
        or	
        key: [value1,value2]


yml后缀配置文件不能与properties后缀配置文件共存

配置文件与配置类属性映射方式

  1. @Value注解将配置文件中的值映射到一个Spring管理的Bean的字段上
    person.name=zhangsan  
    or
    person:
        name:zhangsan
      
    在spring管理的类中注入配置文件的属性  
    @Value("${person.name}")
    private String name;
  1. @ConfigurationProperties映射
    通过注解@ConfigurationProperties(prefix="配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映射
    
    @Controller
    @ConfigurationProperties(prefix = "person")
    public class QuickStartController {

    private String name;//自动配置将前缀为person属性为name的配置信息注入到name属性中
  1. Environment对象读取配置
    方法getProperty可以获得配置的内容

2.核心功能

起步依赖

解决依赖组件的版本兼容并能传递基于功能的依赖
无需指定版本号,起步依赖本身的版本由SpringBoot版本决定,且起步依赖会决定引入的传递依赖的版本

排除依赖:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
            </exclusion>
        </exclusions>
    </dependency>

覆盖依赖://maven总会用最近的依赖故而项目pom的依赖版本会覆盖传递依赖引入的另一个依赖
     <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.4.3</version>
    </dependency>

自动配置

Spring Boot的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定Spring配置应该用哪个,不该用哪个。该过程是Spring自动完成的。
自动配置依托于spring-boot-autoconfigure的jar文件,利用了Spring的条件化配置

条件化配置:
    在Spring中通过实现Condition接口,重写其matches方法,配合条件化注解@Conditional(value=class字节码对象即自定义Condition类)完成条件化配置
自动配置中使用的条件化注解://条件成立时才会注册Bean,读取配置类否则忽略   多个条件关系是与
    条件化注解                          配置生效条件
    @ConditionalOnBean              配置了某个特定的Bean
    @ConditionalOnMissingBean       没有特定的Bean
    @ConditionalOnClass             Classpath里有指定的类
    @ConditionalOnMissingClass      Classpath里缺少指定的类
    @ConditionalOnExpression        给定的Spring Expression Language(SpEL)表达式计算结果为true
    @ConditionalOnJava              Java的版本匹配特定值或者一个范围值
    @ConditionalOnJndi              参数中给定的JNDI位置必须存在一个,如果没有给参数,则要有JNDIInitialContext
    @ConditionalOnProperty          指定的配置属性要有一个明确的值
    @ConditionalOnResource          Classpath里有指定的资源
    @ConditionalOnWebApplication    这是一个Web应用程序
    @ConditionalOnNotWebApplication 这不是一个Web应用程序

自定义配置:
    1 显式配置进行覆盖
    2 使用属性进行精细化配置(环境变量,属性文件,YAML文件)

3.Actuator监控和度量

SpringBootActuator的关键特性是在应用程序中提供众多Web端点,通过这些端点了解应用程序的内部状况。

Actuator提供了13个端点,可以分为三大类:配置端点、度量端点和其他端点

http方法  路径端点              描述
get	    /autoconfig	        提供了一份自动配置报告,记录哪些自动配置条件通过了,哪些没通过
get	    /configprops	    描述配置属性(包含默认值)如何注入Bean
get	    /beans	            描述应用程序上下文里全部的Bean,以及它们的关系
get	    /dump	            获取线程活动的快照
get	    /env            	获取全部环境属性
get	    /env/{name}     	根据名称获取特定的环境属性值
get	    /health	            报告应用程序的健康指标,这些值由 HealthIndicator 的实现类提供
get	    /info	            获取应用程序的定制信息,这些信息由 info 打头的属性提供
get	    /mappings	        描述全部的URI路径,以及它们和控制器(包含Actuator端点)的映射关系
get	    /metrics	        报告各种应用程序度量信息,比如内存用量和HTTP请求计数
get	    /metrics/{name}	    报告指定名称的应用程序度量值
post    /shutdown	        关闭应用程序,要求 endpoints.shutdown.enabled 设置为 true
get	    /trace	            提供基本的HTTP请求跟踪信息(时间戳、HTTP头等) 默认容量100条

要启用Actuator的端点,只需在项目中引入Actuator的起步依赖即可。

在Gradle构建说明文件里,这个依赖是这样的:
compile 'org.springframework.boot:spring-boot-starter-actuator'
  
对于Maven项目,引入的依赖是这样的:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

亦或你使用Spring Boot CLI,可以使用如下 @Grab 注解:
@Grab('spring-boot-starter-actuator')

查看端点的三种方式:

1.REST端点
2.远程shell
3.JMX管理MBean

定制Actuator:

一重命名端点
    修改端点ID(ID用来决定端点的路径)
    设置配置属性endpoints.endpoint-id.id
    例如:endpoints.shutdown.id=kill则/shutdown访问路径换至/kill
二启用和禁用端点
    endpoints.endpoint-id.enabled启用或禁用指定端点
    endpoints.enabled启用或禁用所有端点
    例如:endponts:
            enabled:false
            metrics:
                enabled:true
            禁用所有端点只重启/metrics端点
三自定义度量信息
    CounterService接口:创建其实例并注册为Spring的应用程序的上下文中的Bean//SpringBoot提供了两者的实现,只需@Autowired注入即可
        public interface CounterService{//用来增加,减少,重置特定名称的度量值
            void increment(String metricName);
            void decrement(String metricName);
            void reset(String metricName);
        }
    GaugeService:
         public interface GaugeService{//将某个值记录到特定名称的度量值里(double值)
             void submit(String metricName,double value);
         }
    PublicMetrics:此接口需要自己实现  并@Component交由Spring管理
        public interface PublicMetrics{//提供自己所需要的度量信息,不仅限double值
            Collection<Metric<?>> metrics();//返回Metric对象的集合 new Metric<T>(String metricName,T value)  
        }
四创建自定义仓库来存储跟踪数据
    /trace 端点报告的跟踪信息存储在内存中,默认100条封顶
    1.声明InMemoryTraceRepository(本质仍然是存储在内存),将容量调整至100以上。setCapacity(容量)方法调整容量 
    2.实现TraceRepository接口
        public interface TraceRepository{
            List<Trace> findAll();//查找所有存储的Trace对象
            void add(Map<String,Object>traceInfo);//保存一个Trace,包含跟踪信息的Map对象
        }
五插入自定义的健康指示器
    HealthIndicator接口
        public interface HealthIndicator{
            Health health();
        }
        Health:
            down().build();
            down().withDetail(String key,e.getMessage 错误信息).build();//withDetail()方法可以向健康记录中加附加信息
            up().build();

设置端点的上下文路径:

management.context-path=/mgmt  
则所有端点前缀mgmt 例如/mgmt/metrics

4.常用配置整合

整合SpringDataJPA

1)添加springdataJpa的启动依赖。

<!-- springBoot JPA的起步依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL连接驱动 即数据库驱动依赖 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

2)在工程添加一个Entity实体类。

3)编写dao

public interface UserDao extends JpaRepository<User, Long> {
 }

4)在配置文件application.properties中
配置数据库的连接串

    #DB Configuration:
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
    spring.datasource.username=root
    spring.datasource.password=root
    
    #JPA Configuration:
    spring.jpa.database=MySQL
    spring.jpa.show-sql=true
    spring.jpa.generate-ddl=true
    spring.jpa.hibernate.ddl-auto=update

整合表现层框架

一般做页面都是使用jsp实现。
jsp本质上就是servlet,servlet需要一个web工程。
在springboot中不推荐使用jsp。推荐使用模板技术。
推荐使用freemarker、Thymeleaf

需要整合freemarker做页面。
使用方法:
1)向工程中添加freemarker的启动器。
    ```
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    ```
2)编写模板文件。模板文件必须放到resources/templates目录下,而且扩展名必须ftl
	模板+数据=页面
	注意:数据由处理器上参数Model/ModelAndView/ModelMap/Map进行传输(数据存放在request域中重定向会丢失数据)

整合单元测试

<!--测试的起步依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
新版SpringBoot@SpringApplicationConfiguration被@SpringBootTest替换
@RunWith(SpringRunner.class)//还有基于规则的SpringClassRule和SpringMethodRule
@SpringBootTest(classes=ReadinglistApplication.class)//通过SpringBoot加载上下文 即初始化SpringBoot容器
public class ReadinglistApplicationTests {

	@Test//测试加载的上下文
	public void contextLoads() {
	}

SpringRunner继承自SpringJUnit4ClassRunner,使用哪一个Spring提供的测试测试引擎都可以

@SpringBootTest的属性指定的是引导类的字节码对象

Web测试

1.SpringMockMVC:在模拟的Servlet容器里测试控制器,不用实际启动应用服务器

类:
    WebApplicationContext
    MockMvc  //通过MockMvcBuilders的静态方法webAppContextSetup(传入web上下文对象).build()获得MockMvc实例
    MockMvcRequestBuilders
    MockMvcResultMatchers
注解:
    @WebAppConfiguration  开启Web上下文测试

2.Web集成测试:在真正的应用服务器里执行测试

注解:
    @WebIntegrationTest  在服务器里运行测试
        属性value接受一个String数组,元素为配置属性如server.port=0配置启动服务器端口号随机
        @WebIntegrationTest(value={"server.port=0"})= @WebIntegrationTest(randomPort=true)
        

测试Web安全

整合SpringSecurity
    1依赖坐标spring-security-test
    2通过MockMvcBuilders静态方法apply(SecurityMockMvcConfigurers.springSecurity())整合Web测试和Web安全
    
    注解:
        @WithMockUser:加载安全上下文 ,其中包含一个UserDetails,使用给定的用户名,密码和授权
        @WithUserDetails:根据给定的用户名查找UserDetails对象再加载安全上下文

整合mybatis

1 添加mybatis启动器
    <!--mybatis起步依赖-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.1.1</version>
    </dependency>

2 创建实体Bean

3 编写Mapper
    注意:@Mapper标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中

4 配置Mapper映射文件
    在src\main\resources\mapper路径下加入UserMapper.xml配置文件"

5 在application.properties中添加mybatis的信息
    #spring集成Mybatis环境
    #pojo别名扫描包
    mybatis.type-aliases-package=com.guyu.domain
    #加载Mybatis映射文件
    mybatis.mapper-locations=classpath:mapper/*Mapper.xml

Mapper接口和映射文件在同一目录下

    此种情况下需要在maven的配置文件中添加如下信息:
    <build>
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.properties</include>
					<include>**/*.xml</include>
				</includes>
				<filtering>false</filtering>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.*</include>
				</includes>
				<filtering>false</filtering>
			</resource>
		</resources>
	</build>
	
	并且无需在application.properties中配置mapper路径,只需要在引导类上添加@MapperScan注解即可
	
	@SpringBootApplication
    @MapperScan("com.guyu.mapper")
    public class Application1 {
    
        public static void main(String[] args) {
            SpringApplication.run(Application1.class, args);
        }
    }

整合redis

1 添加起步依赖

<!-- 配置使用redis启动器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2 配置redis的连接信息

#Redis 配置
spring.redis.host=127.0.0.1
spring.redis.port=6379

3 注入RedisTemplate

@Autowired
private StringRedisTemplate redisTemplate;

4 使用redisCluster

如果想使用redis集群只需要将application.properties文件中redis的连接配置该为如下配置:
##########redis############  
#redis的IP地址
#spring.redis.host=localhost
#redis的端口
#spring.redis.port=6379
#使用redis cluster
spring.redis.cluster.nodes=192.168.25.153:7001,192.168.25.153:7002,192.168.25.153:7003,\
							192.168.25.153:7004,192.168.25.153:7005,192.168.25.153:7006

整合ElasticSearch

1 添加起步依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

2 配置文件

#elasticsearch  集群
spring:
  data:
    elasticsearch:
      cluster-name: my-elasticsearch
      cluster-nodes: 127.0.0.1:9300,127.0.0.1:9301,127.0.0.1:9302

3 创建Entity

@Document(indexName = "索引库", type = "user")//index相当于库,type相当于表
public class User {

    @Id
    @Field(type = FieldType.Integer, store = true)
    private long id;
    @Field(type = FieldType.Text, store = true, analyzer = "ik_max_word")
    private String username;
    //get、set...

4 创建Repository

public interface UserRepository extends ElasticsearchRepository<User, Long> {

}

5 注入

@Autowired
private UserRepository userRepository;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;

注意:
Spring boot整合redis与elaticsearch时报错

解决方法:

在运行参数中添加:
//jvm参数
-Des.set.netty.runtime.available.processors=false

4.事务管理

1、在引导类上添加@EnableTransactionManagement注解。
2、在需要开启事务的方法上添加@Transactional注解。

5.异常处理

无论是发生什么错误,SpringBoot都会返回一个状态码以及一个错误页面/error,默认的发生错误,它会将请求转发到BasicErrorController控制器来处理请求

自定义错误页面:

在static和template下创建页面error.html或error.ftl,错误信息从request域中获取
此方式只针对浏览器发送的请求

自定义局部异常:

1.编写Controller类[被注解@Controller或@RestController修饰]
2.通过@ExceptionHandler注解处理该Controller类抛出的异常
    局部异常处理 @Controller + @ExceptionHandler
范围单个类

代码:

@Controller
public class BaseController {
    @RequestMapping(value="/ex")
    @ResponseBody
    public String error(){
        int i=5/0;
        return "ex";
    }
   //捕获到异常以json形式返回
    @ExceptionHandler(Exception.class)
    @ResponseBody//Result自定义异常信息类,通过ResponseBody返回Json格式数据
    public Result error(Exception e){
        if(e instanceof ArithmeticException){
        return new Result(false, StatusCode.ERROR, "错误信息:"+e.getMessage());
        }
        return new Result(false, StatusCode.ERROR, "未知错误");
    }
}

自定义全局异常:

1.编写一个handler类处理controller层抛出的异常
2.通过@ControllerAdvice注解来处理异常
    全局异常处理 @ControllerAdvice + @ExceptionHandler
范围全局
进入Controller层的错误才会由@ControllerAdvice处理,拦截器抛出的错误以及访问错误地址的情况@ControllerAdvice处理不了,由SpringBoot默认的异常处理机制处理。

代码:

@ControllerAdvice
public class BaseExceptionHandler {
   //捕获到异常以json形式返回
    @ExceptionHandler
    @ResponseBody//Result自定义异常信息类,通过ResponseBody返回Json格式数据
    public Result error(Exception e){
        return new Result(false, StatusCode.ERROR, "错误信息:"+e.getMessage());
    }
}

6.SpringBoot部署

部署产物产生方式目标环境
Groovy源码手写Cloud Foundry及容器部署,比如Docker
可执行JARMaven、Gradle或SpringBootCLI云环境,包括Cloud Foundry和Heroku,还有容器部署,比如Docker
WARMaven、GradleJava应用服务器(tomcat)或云环境,比如Cloud Foundry

部署可执行Jar包是一个fat jar。其中包含项目要运行使用的所有的jar包。

第一步:在工程的pom.xml中添加以下依赖

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>

第二步:可以直接使用maven的命令打成jar包。

mvn package

如果需要添加jvm启动参数例如:

>java -Des.set.netty.runtime.available.processors=false -jar springboot_test.jar

7.SpringBoot热部署

在pom.xml中配置
<!--热部署配置-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

注意:IDEA进行SpringBoot热部署失败原因

Intellij IEDA默认情况下不会自动编译,需要对IDEA进行自动编译的设置

 Shift+Ctrl+Alt+/,选择Registry

springBoot的jms应用 内置JMS消息 配置属性文件application.properties配置指定JMS的服务器
jmsTemplate convertAndSend(‘参数一’,‘参数二’)

参数一 test_queue 参数二 text 消息变量

@component
consumer

@JmsListener(destination=“test_queue”)
public void 自定义(String message){

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值