SpringBoot use·Part 1 (SpringBoot annotation + integrated JDBC + integrated druid (Druid) + sql monitoring)

Article Directory

Use of SpringBoot

SpringBoot is used to simplify the Spring framework. Therefore, unlike Spring's usage, SpringBoot has its own set of usage.

SpringBoot annotation

@SpringBootApplication

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootDemoApplication {

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

}

This annotation is owned by the startup class of SpringBoot, and is also the core annotation of SpringBoot. It identifies that this is a SpringBoot application and is used to enable various functions of SpringBoot. In fact, this annotation is a combination of the three annotations @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. Since the three annotations are generally used together, SpringBoot provides such a unified annotation.

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)

The above code is the underlying source code seen when entering the @SpringBootApplication annotation.

@SpringBootConfiguration

This is a class-level annotation in SpringBoot, indicating that this class provides application-level configuration. Generally, a class with a main() method is most suitable for this annotation. @SpringBootApplication will automatically inherit this annotation

@EnableAutoConfiguration

Allow SpringBoot to automatically configure annotations. After opening this annotation, SpringBoot can configure SpringBean according to the package or class under the current classpath. For example, if there is the MyBatis jar package in the current classpath, the MybatisAutoConfiguration annotation can configure the SpringBeans of MyBatis according to the relevant parameters.

@ComponentScan

The component scans the annotations and lets SpringBoot scan the @Configuration class and add it to the program context. The @ComponentScan annotation will by default assemble the classes annotated with @Controller, @Service, @Respository, and @Component into the Spring container.

@Configuration

Used to define the configuration class, pointing out that this class is the information source of the Bean configuration, which is equivalent to the traditional xml configuration file and is generally added to the main class. If some third-party libraries need to use xml files, the @Configuration class is generally used as the main class of the project.

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;

//配置德鲁伊数据源
@Configuration
public class DruidDataSourceConfig {

	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource druid() {
		return new DruidDataSource();
	}
}

@Bean

It is equivalent to <bean></bean> in Xml, placed above the method, which means that the method will return a bean and give it to Spring for management.

@ConfigurationProperties

The value assigned to the Person attribute in the configuration file can be mapped to this component.

Need to import the relevant jar first

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

We add a new attribute to the application configuration file

user1:
  name: jim
  age: 18

Create a new entity class, and use the label to inject

package com.cwd.SpringBootDemo.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "user1")
public class User {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Test Results

Insert picture description here

SpringBoot integrated JDBC

When we access the database, we always need to configure a data source first. The data source is an abstraction of the database and the interactive operation of the database. It encapsulates the location information of the target source, verification information, and operations to establish and close connections. The data source can be regarded as a component in the program, which abstracts the traditional operations such as writing configuration information and obtaining connections in the code into a specification or interface. Let's take MySQL database as an example:

1. Introduce the relevant driver package of MySQL, in the pom.xml file.

<!-- mysql-connector-java mysql驱动包 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>

2. Introduce JDBC into the pom.xml file to support database connection

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

3. Configure the data source datasource in the application. If no other database source management is configured, it will automatically use the database source that comes with JDBC for management, that is, use the JdbcTemplate to operate the database. Here, it has been handed over to Spring for unified management and used directly @Autowired can be used in the class for injection.

#spring配置
#配置数据库,配置数据库源默认使用JDBC自带的数据库源管理
spring:
  datasource:
    #数据库地址
    url: jdbc:mysql://127.0.0.1:3306/mybatis_db?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    #数据库用户名
    username: root
    #数据库密码
    password: root
    #数据库加载类
    driver-class-name: com.mysql.cj.jdbc.Driver

4. Use case

@Service
@Transactional
public class HelloService {
    @Autowired
    JdbcTemplate jdbcTemplate;

    public User findUserById(Integer id) {
        User user = new User();
        jdbcTemplate.query("select name,age from t_user where  id = ?",
                new Object[]{id}, new RowCallbackHandler() {
                    public void processRow(ResultSet rs) throws SQLException {
                        user.setName(rs.getString("name"));
                        user.setAge(rs.getInt("age"));
                    }
                });
        return user;
    }
}

Integrated druid (druid) data source

When we use other better data source management, we will no longer use the data source management that comes with JDBC.

1. Import the jar of the druid data source

#spring配置
#配置数据库,配置数据库源默认使用JDBC自带的数据库源管理
spring:
  datasource:
    #数据库地址
    url: jdbc:mysql://127.0.0.1:3306/mybatis_db?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    #数据库用户名
    username: root
    #数据库密码
    password: root
    #数据库加载类
    driver-class-name: com.mysql.cj.jdbc.Driver
    #注册druid数据库链接池
    type: com.alibaba.druid.pool.DruidDataSource
    #初始化时建立物理连接的个数
    initialSize: 5
    #最小连接池个数
    minIdle: 1
    #最大连接池数量
    maxActive: 20
    #开启Sql监控
    filters: stat

2. Host the Druid data source to the DataSource, we need to use java code to complete this process, which is equivalent to our previous operation in the xml file

<!--配置DruidDataSource交给spring容器管理,spring管理数据库链接(数据源)-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis_db?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai"></property>
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
    <property name="username" value="root"></property>
    <property name="password" value="root"></property>
</bean>
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;

//配置德鲁伊数据源
@Configuration
public class DruidDataSourceConfig {

	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource druid() {
		return new DruidDataSource();
	}
}

Sql monitoring

To use Sql monitoring, you need to write the following code in the DruidDataSourceConfig class, that is, the class that configures the druid data source:

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


@Configuration
public class DruidDataSourceConfig {

	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource druid() {
		return new DruidDataSource();
	}

	@Bean
	public ServletRegistrationBean druidStatViewServlet() {
		//ServletRegistrationBean提供类的进行注册
		ServletRegistrationBean servletRegistrationBean =
				new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
		//添加初始化参数:initParams
		//白名单:
		servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
		//IP黑名单(同时存在时,deny优先于allow)
		//如果满足deny,就提示:sorry,you are not permitted to view this page
		servletRegistrationBean.addInitParameter("deny", "192.168.1.73");
		//登录查看信息的账号和密码
		servletRegistrationBean.addInitParameter("loginUsername", "admin");
		servletRegistrationBean.addInitParameter("loginPassword", "123456");
		servletRegistrationBean.addInitParameter("resetEnable", "false");
		return servletRegistrationBean;
	}


	@Bean
	public FilterRegistrationBean druidStatFilter() {
		FilterRegistrationBean filterRegistrationBean =
				new FilterRegistrationBean(new WebStatFilter());
		//添加过滤规则
		filterRegistrationBean.addUrlPatterns("/*");
		//添加需要忽略的格式信息
		filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif," +
				"*.jpg,*.png, *.css,*.ico,/druid/*");
		return filterRegistrationBean;

	}
	 
}

If we did not choose to integrate web when creating the project, we also need to import it in the pom.xml file

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

When we complete these operations, we can enter

http://localhost:port number/druid/login.html,

Enter the account (admin) and password (123456) that we configured in the class to log in, and view the sql records of the operation database on the web page.

Insert picture description here