SpringBoot

SpringBoot

1.springboot入门

在该入门案例中,没有任何配置,就可以实现一个SpringMVC项目

1.导入依赖

<parent>
	<groupid>org.apringframework.boot<l groupid>
	<artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</ version>
</parent>
<!--        
<groupId>com.itheima</groupId>
<artifactId>heima-springboot</artifactId>
<version>1.0-SNAPSHOT</version>
-->       
<properties>
    <java.version>1.8</java.version>
</properties>
        
<dependencies>
	<dependency>
        <groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2.创建启动引导类

package com.itheima ;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootapplication;
/**
* spring boot工程都有一个启动引导类,这是工程的入口类
*并在引导类上添加@SpringBootApplication
*自动扫描所在包及其子包
*/
@SpringBootApplication
public class Application {
	public static void main(String[] args) {
	SpringApplication.run(Application.class,args);
    }
}

3.创建处理器Controller,访问即可

package com.itheima.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {   
	@GetMapping("hello")
	public String hello(){	
        return "Hello, Spring Boot!";
	}
}

2.SpringBoot的配置

2.1Java代码方式配置

2.1.1@Value的方式注入基本属性

java配置主要靠java类和一些注解,比较常用的注解有:

  • @Configuration:声明一个类作为配置类,代替xml文件
  • @Bean:声明在方法上,将方法的返回值加入Bean容器,代替标签
  • @Value:属性注入
  • @PropertSource:指定外部属性文件

我们接下来用java配置来尝试实现连接池配置:

1.在pom.xml文件中添加Druid连接池依赖如下

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.6</version>
</dependency>

2.创建jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc,url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=000000

3.创建配置类

@Configuration
@PropertSource("classpath:jdbc.properties")
public class JdbcConfig {
	@Value("${jdbc.ur1}")
    String url;
	@Value("${jdbc.driverclassName} ")
    String driverClassName;
	@Value("${jdbc.username}")
    String username;
	@Value("S{jdbc.passwor d}")
    String password;
	@Bean
	public Datasource datasource(){
		DruidDatasource datasource = new DruidDataSource(); 	 
        datasource.setDriverClassName(driverClassName);
        datasource.setUrl(ur1) ;
        datasource.setUsername(username);
        datasource.setPassword(password);
        return datasource;
	}
}

2.1.2@ConfigurationProperties对象属性注入

目标:能够使用@ConfigurationProperties实现Spring Boot配置文件配置项读取和应用

分析:
需求∶将配置文件中的配置项读取到一个对象中;
实现∶可以使用Spring Boot提供的注解@ConfigurationProperties,该注解可以将Spring Boot的配置文件(默认必须为application。properties或application。yml)中的配置项读取到一个对象中。

实现步骤︰
1.创建配置项类]dbcProperties类,在该类名上面添加@ConfigurationProperties ;

/**
*ConfigurationProperties 从applicatior配置文件中读取配置项
*prefix表示配置项的前缀(如:jdbc.username中的jdbc)
*配置项类中的类变量名必须要与前缀之后的配置项名称保持松散绑定(相同)
*/
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    private string url;
    private string driverClassName;
    private string username;
    private string password;
    //生成getter和setter方法
}

@ConfigurationProperties报红,还需要添加依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
    <!--不传递依赖-->
	<optional>true</optional>
</dependency>

2.将jdbc.properties修改名称为application.properties ;
3.将JdbcProperties对象注入到JdbcConfig ;

package com.itheima.config
@Configuration
//@PropertSource("classpath:jdbc.properties")
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
/**	@Value("${jdbc.ur1}")
    String url;
	@Value("${jdbc.driverclassName} ")
    String driverClassName;
	@Value("${jdbc.username}")
    String username;
	@Value("S{jdbc.passwor d}")
    String password;
*/    
	@Bean
	public Datasource datasource(JdbcProperties jdbcProperties){
		DruidDatasource datasource = new DruidDataSource(); 	 
        datasource.setDriverClassName(jdbcProperties.getDriverClassName());
        datasource.setUrl(jdbcProperties.getUrl()) ;
        datasource.setUsername(jdbcProperties.getUsername());
        datasource.setPassword(jdbcProperties.getPassword());
        return dataSource;
	}
}

4.测试

2.1.3更优雅的注入

事实上,如果一段属性只有一个Bean需要使用,我们无需将其注入到一个类(JdbcProperties,将该类上的所有注解去掉)中。而是直接在需要的地方声明即可;再次修改JdbcConfig类为如下代码:

@Configuration
public class Jdbcconfig {
    @Bean
    //声明要注入的属性前缀,Spring Boot会自动把相关属性通过set方法注入到Datasource中
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

我们直接把@ConfigurationProperties(prefix = "jdbc")声明在需要使用的@Bean 的方法上,然后SpringBoot就会自动调用这个Bean(此处是DataSource)的set方法,然后完成注入。使用的前提是:该类必须有对应属性的set方法!

2.2.yml文件配置

目标:可以将多个yml文件在application.yml文件中配置激活

分析:
yaml与properties配置文件除了展示形式不相同以外,其它功能和作用都是一样的;在项目中原路的读取方式不需要改变。

yml配置文件的特征∶
1.树状层级结构展示配置项;
2.配置项之间如果有关系的话需要分行空两格;
3.配置项如果有值的话,那么需要在:之后空一格再写配置项值;将application.properties配置文件修改为application.yml的话:

jdbc:
  driverclassName: com.mysql.jdbc.Driver
  url: jdbc:mysql://127.0.0.1:3306/springboot_test
  username: root
  password: root
#激活配置文件;需要指定其它的配置文件名称
spring:
  profiles:
    active: abc,def

2 )多个yml配置文件;在spring boot中是被允许的。这些配置文件的名称必须为application-***.yml(如:application-abc.yml),并且这些配置文件必须要在application.yml配置文件中激活之后才可以使用。
3 )如果properties和yml配置文件同时存在在spring boot项目中﹔那么这两类配置文件都有效。在两个配置文件中如果存在同名的配置项的话会以properties文件的为主。

3.lombok应用

目标:使用lombok的注解实现pojo类的简化

分析:
编写数据库表对应的实体类;一般情况下需要编写get/set/toString等这些方法会让实体类看起来比较臃肿。可以使用lombok插件对实体类进行简化。
lombok是一个插件工具类包;提供了一些注解@Data、@Getter等这些注解去简化实体类中的构造方法、get/set等方法的编写。

步骤:

1.在IDEA中安装lombok插件;

2.添加lombok对应的依赖到项目pom.xml文件

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

3.改造实体类使用lombok注解

import lombok.Data;
import java.util.Date;
//在编译阶段会根据注解自动生成对应的方法; data包含get/set/hashCode/equals/toStzing等方法
@Data
public class User {
    private Long id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private Integer sex;
    private Date birthday;
    private String note;
    private Date created;
    private Date updated;
}

然后可以在Bean上使用:
@Data:自动提供getter和setter、hashCode、equals、toString等方法 @Getter:自动提供getter方法
@Setter:自动提供setter方法
@Slf4j:自动在bean中提供log变量,其实用的是slf4j的日志功能。
例如:在javabean上加@Data,那么就可以省去getter和setter等方法的编写,lombok插件会自动生成。

4.SpringBoot整合SpringMVC拦截器

目标:可以在Spring Boot项目中配置自定义SpringMVC拦截器分析:
1.编写拦截器(实现Handlerlnterceptor ) ;
2.编写配置类实现WebMvcConfigurer,在该类中添加各种组件;

@Configuration
public class Mvcconfig implements WebMvcConfigurer {
    //注册拦截器
    @Bean
    public MyInterceptor myInterceptor() {
    	return new MyInterceptor();
    }
    //添加拦截器到spring mvc拦截器链
    @Override
    public void addInterceptors(InterceptorRegistry registry){
   		registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
	}
}

3.测试

5.SpringBoot整合-事务和连接池

目标:配置Spring Boot自带默认的hikari数据库连接池和使用@Transactional注解进行事务配置

分析:
事务配置
1.添加事务相关的启动器依赖,mysql相关依赖;

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysq1-connector-java</artifactId>
    <version>5.1.46</version>
</dependency>

2.编写业务类UserService使用事务注解@Transactional

数据库连接池hikari配置
1.只需要在application配置文件中指定数据库相关参数

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    ur1: jdbc:mysql://127.0.0.1:3306/springboot_test
    username: root
    password: root

6.SpringBoot整合-Mybatis

目标∶配置Mybatis在Spring Boot工程中的整合包,设置mybatis的实体类别名,输出执行sql语句配置项分析:
1.添加启动器依赖;

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.1</version>
</dependency>

2.配置Mybatis :实体类别名包,日志,映射文件等;

mybatis:
  #实体类别名包路径
  type-aliases-package: com.itheima.pojo
  #映射文件路径
  # mapper-locations: classpath:mappers/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdoutImpl

3.配置@MapperScan

可以在接口上配置@Mapper,但这种方法不推荐。

在启动类上配置

//扫描mybatis所有的业务接口
@MapperScan("com.dtf.mapper")

7.SpringBoot整合-通用Mapper

目标︰配置通用Mapper组件到Spring Boot项目中并使用Mapper接口

分析:
通用Mapper:可以实现自动拼接sql语句;所有的mapper都不需要编写任何方法也就是不用编写sql语句。可以提高开发效率。

1.添加启动器依赖;

<!--通用mapper -->
<dependency>
	<groupId>tk.mybatis</groupId>
	<artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>

2.改造UserMapper继承Mapper ;

public interface UserMapper extends Mapper<User> {
    
}

3.修改启动引导类Application中的Mapper扫描注解;

//尤其注意,导入tk.mybatis.spring.annotation.MapperScan包
import tk.mybatis.spring.annotation.MapperScan;
@MapperScan("com.dtf.mapper")

4.修改User实体类添加jpa注解;

@Table(name = "tb_user")
public class User {
    @Id
    //主键回填
    @Keysql (useGeneratedKeys = true)
    private Long id;
    @Column (name = "user_name")
    //user_name --> userName
    private String userName;
    private String password;
    private Integer age;
    private Date updated;
}

5.UserService实现业务功能;

8.SpringBoot整合-Junit

目标:在Spring Boot项目中使用unit进行单元测试UserService的方法

分析:
1.添加启动器依赖spring-boot-starter-test ;

<dependency>
	<groupId>org-springframework.boot<lgroupId>
	<artifactId>spring-boot-starter-test</artifactId>
</dependency>

2.编写测试类

@RunWith(springRunner.class)
@SpringBootTest
public class UserserviceTest {
    @Test
}

小贴士:在类名上按住shift+ctrl+T就可快速创建测试类

9.SpringBoot整合-redis

目标∶在Spring Boot项目中使用Junit测试RedisTemplate的使用

分析 :
1.添加启动器依赖;spring-boot-starter-data-redis

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

2.配置application.yml中修改redis的连接参数;( redis需要启动)

spring:
  redis:
    host: localhost
    port: 6379

3.编写测试类应用RedisTemplate操作redis中的5种数据类型( string/hash/list/set/sorted set )

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
	@Autowired
	private RedisTemplate redisTemplate;
	@Test
    public void test (){
        
        // String字符串
        // redisTemplate.opsForValue().set("str", "heima");
        redisTemplate.boundvalueOps(key:"str" ).set("heima");
        System.out.println("str = " + redisTemplate.opsForValue().get("str"));

        // hash 散列
        redisTemplate.boundHashOps("h_key").put("name","heima");
        redisTemplate.boundHashOps("h key").put("age",13);
        //获取所有域
        Set set = redisTemplate.boundHashOps("h_key").keys();
        System.out.println ("hash散列的所有域:" + set);
        //获取所有值
        List list = redisTemplate.boundHashOps("h _key").values();
        System.out.println ("hash散列的所有域" + list);

        //list列表
        redisTemplate.boundListOps("1_key").leftPush("c");
        redisTemplate.boundListOps("l_key").leftPush("b");
        redisTemplate.boundListOps("1_key").leftPush("a");
        //获取全部元素
    	list = redisTemplate.boundListOps("1_key" ).range(0,-1);
        System.out.println("list列表中的所有元素:" +list);

    	// set集合
    	redisTemplate.boundSetOps("s_key").add("a","b","c");
        set = redisTemplate.boundSetOps("s_key" ).members();
        System.out.println("set集合中的所有元素:" + set);
        
    	// sorted set有序集合
    	redisTemplate.boundzsetOps("z_key").add("a",30);
        redisTemplate.boundzsetOps("z_key").add("b",20);
        redisTemplate.boundzsetOps("z_key").add("c",10);
    	set = redisTemplate.boundzSetOps("z_key").range(0,-1);
        System.out.println("zset有序集合中的所有元素:" + set);
    }
}

10.SpringBoot项目部署

目标:将Spring Boot项目使用maven指令打成jar包并运行测试

分析:
1.需要添加打包组件;将项目中的资源、配置、依赖包打到一个jar包中;可以使用maven的package ;

<build>
    <plugins>
    	<!--打jar包时如果不配置该插件,打出来的jar包没有清单文件-->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

2.部署: java -jar 包名

posted @ 2020-10-22 18:15  文森特·Du  阅读(250)  评论(0编辑  收藏  举报