spring的简单使用

00_写在前面

本文介绍的是spring的简单使用,不会涉及很多的spring的说明信息。

基本版本信息:

组件名称 版本信息
JDK版本 1.8
springboot的版本 2.7.4

其他说明:
在本文章中,会使用到web功能,因此会引用web的springboot依赖,为了代码简洁,还会引入lombok的依赖

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

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

01_在springboot中使用H2数据库

引入H2的maven依赖

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>runtime</scope>
</dependency>

代码实现

springboot启动时执行的sql

这些sql代码写在resources目录下,一个时schema.sql另外一个是data.sql

schema.sql

create table person(id integer primary key ,name varchar(50),address varchar(50),remark varchar(100));

data.sql

插入sql脚本
insert into person(id,name,address,remark) values (1,'zhangsan1','beijing1','beizhu1');
insert into person(id,name,address,remark) values (2,'zhangsan2','beijing2','beizhu2');
insert into person(id,name,address,remark) values (3,'zhangsan3','beijing3','beizhu3');
insert into person(id,name,address,remark) values (4,'zhangsan4','beijing4','beizhu4');
insert into person(id,name,address,remark) values (5,'zhangsan5','beijing5','beizhu5');
insert into person(id,name,address,remark) values (6,'zhangsan6','beijing6','beizhu6');
insert into person(id,name,address,remark) values (7,'zhangsan7','beijing7','beizhu7');
springboot的Controller代码

在Controller类中体现了DataSourceJdbcTemplate的使用。

点击查看代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/h2")
@Slf4j
public class H2Controller {
    @Autowired
    //springboot会自动帮我们封装dataSource,所有我们不用配置DataSource就可以直接使用
    private DataSource dataSource;

    @Autowired
    //springboot会自动帮我们封装jdbcTemplate,所有我们不用配置JdbcTemplate就可以直接使用
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/dataSource")
    public String testDataSource() throws Exception {

        Connection connection = dataSource.getConnection();
        log.info(connection.toString());
        
        PreparedStatement preparedStatement = connection.prepareStatement("select * from person");
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            String string = resultSet.getString(2);
            log.info(string);
        }

        return "success";
    }

    @GetMapping("/jdbcTemplate")
    public String testJdbcTemplate() {

        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from person");
        log.info(String.valueOf(maps.size()));

        return "success";
    }
}

02_在springboot中使用mysql数据库

引入mysql的maven依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.30</version>
</dependency>

代码实现

配置mysql的参数application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/demo?serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
springboot的Controller代码
点击查看代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/h2")
@Slf4j
public class MysqlController {

    @Autowired
    //springboot会自动帮我们封装jdbcTemplate,所有我们不用配置JdbcTemplate就可以直接使用
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/jdbcTemplate")
    public String testJdbcTemplate() {

        String result = jdbcTemplate.queryForObject("select version()", String.class);
        log.info(result);

        return "success";
    }
}

03_在springboot中使用mysql数据库和druid连接池

引入druid和mysql的maven依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.30</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

代码实现

配置mysql和druid的参数application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/demo?serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root

spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.filters=conn,config,stat,slf4j

spring.datasource.druid.test-on-borrow=true
spring.datasource.druid.test-on-return=true
spring.datasource.druid.test-while-idle=true

配置druid的过滤器

配置文件位置:resources\META-INF\druid-filter.properties

druid.filters.conn=com.example.demo.config.ConnectionLogFilter

ConnectionLogFilter.java

ConnectionLogFilter 代码
import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.filter.FilterEventAdapter;
import com.alibaba.druid.proxy.jdbc.ConnectionProxy;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;
@Slf4j
public class ConnectionLogFilter extends FilterEventAdapter {
    @Override
    public void connection_connectBefore(FilterChain chain, Properties info) {
        log.info("BEFORE CONNECTION!");
    }

    @Override
    public void connection_connectAfter(ConnectionProxy connection) {
        log.info("AFTER CONNECTION!");
    }
}

ConnectionLogFilter.java

MysqlController代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

@RestController
@RequestMapping("/h2")
@Slf4j
public class MysqlController {

    @Autowired
    //springboot会自动帮我们封装jdbcTemplate,所有我们不用配置JdbcTemplate就可以直接使用
    private JdbcTemplate jdbcTemplate;

    @Autowired
    //springboot会自动帮我们封装dataSource,所有我们不用配置DataSource就可以直接使用
    private DataSource dataSource;

    @GetMapping("/jdbcTemplate")
    public String testJdbcTemplate() throws Exception{

        String result = jdbcTemplate.queryForObject("select version()", String.class);
        log.info(result);

        //打印连接池信息
        log.info(dataSource.toString());

        return "success";
    }
}

04_springboot中使用mybatis

在springboot中使用mybatis,使用的数据库是mybatis,连接池是druid。

在idea中使用easycode插件生成mysql相关的代码

引入mybatis的maven依赖

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

在启动类中配置@MapperScan扫描的DAO层路径

@SpringBootApplication
//配置扫描的dao层路径
@MapperScan("com.h2.h2.ms.dao")
public class H2Application {

	public static void main(String[] args) {
		SpringApplication.run(H2Application.class, args);
	}
}

springboot配置文件的相关配置

需要重点关注mybatis.mapper-locations配置了映射xml文件的位置

#配置xml文件的映射位置
mybatis.mapper-locations=classpath:mapper/*.xml
        
spring.datasource.url=jdbc:mysql://localhost:3306/demo?serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root

05_springboot中使用Redis

06_springboot中使用MongoDB

07_RestTemplate的使用

单机版的使用RestTemplate

public class TestA {
    public static void main(String[] args) {

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> entity = restTemplate.getForEntity("https://www.baidu.com/", String.class);
        System.out.println(entity.getBody());

    }
}

在springboot中使用RestTemplate

springboot不会帮我们自动生成RestTemplate的对象,需要我们进行配置

点击查看代码
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestConfig {

    @Bean
    //springboot会帮我们自动传入RestTemplateBuilder对象
    public RestTemplate getRestTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

}

在controller中使用RestTemplate

点击查看代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

@RestController
@RequestMapping("/rest")
public class TestController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/test")
    public String testA(){
        URI uri = UriComponentsBuilder
                .fromUriString("http://127.0.0.1:8080/person/selectOne?id={id}")
                .build("16");
        RequestEntity<Void> req = RequestEntity.get(uri)
                .accept(MediaType.ALL)
                .build();
        ResponseEntity<String> entity = restTemplate.exchange(req, String.class);

        System.out.println(entity.getHeaders().toString());
        System.out.println(entity.getStatusCode());
        System.out.println(entity.getStatusCodeValue());
        System.out.println(entity.getBody());

        return "success";
    }
}

08_springMVC的使用

在springboot中设置可以访问的静态资源

spring.mvc.static-path-pattern=/static/**

设置响应码

点击查看代码
    @GetMapping("/testA")
    //设置响应码
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public String testA(){

        log.info("haha");
        
        return "success";
    }

SpringMVC的拦截器

SpringMVC的过滤器

09_springboot的Actuator

10_Other

posted @ 2022-10-04 11:18  Su0ne  阅读(110)  评论(0)    收藏  举报