SpringBoot getting started to proficient - SpringBoot custom starter

Define your own starter

1. Get to know spring boot starter

SpringBoot can easily integrate other components. For example, for spring MVC, we only need to import spring boot starter web to write the Controller directly. This package not only imports a jar, but also imports all the jars needed to integrate spring MVC

For the integration of different components, there is a corresponding start. For example, spring boot starter Redis is used to integrate Redis, which imports all the jars required by Redis. The starter contains not only all the jars required to integrate a component, but also the configuration classes that integrate the component. The summary is as follows

  • It integrates the dependency libraries required by this module;
  • Provide configuration items for the module to the user;
  • Provide automatic configuration class to automatically assemble beans in the module;

Let's develop our own starter

2. Define your own starter

Let's define a starter for automatically assembling redis. After a project imports the starter, it can automatically connect to the redis server according to the default configuration. How can we achieve such an effect? Perhaps you should think of encapsulating your own jar package following the automatic configuration process of SpringBoot. So what do we need to do

  1. Create a maven factory and import the jar packages required for redis operation. I will use jedis to demonstrate here
  2. Define a Properties class to load the redis configuration item of yml configuration
  3. Create a new automatic assembly class, and use @ Configuration and @ Bean for automatic assembly
  4. Create met-inf / spring Factories file, configure the automatic configuration class, so that SpringBoot can load it automatically;

2.1. Create project, import dependency

My project is called SpringBoot starter redis. I need to import the SpringBoot foundation dependency and jedis foundation dependency.

<packaging>jar</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starters</artifactId>
    <version>2.2.5.RELEASE</version>
</parent>

<dependencies>
    <!-- SpringBoot Auto configure base dependencies -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <!-- SpringBoot Core foundation dependency -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.2.5.RELEASE</version>
        <scope>compile</scope>
    </dependency>
    <!-- use jedis operation Redis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>commons-pool</groupId>
        <artifactId>commons-pool</artifactId>
        <version>1.6</version>
    </dependency>
</dependencies>

2.2. Define Redis auto configuration

First, create a RedisProperties to read the configuration of yaml

//@ConfigurationProperties: bind the configuration with the same name under the prefix "spring.redis" to the field of the object
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {
    //redis host
    private String host ="127.0.0.1";
    //redis password
    private String password;
    //redis port
    private int port = 6379;
    //Timeout, 1 second timeout
    private int timeout = 1000;
    //Maximum idle
    private int maxIdle = 8;
    //Maximum link
    private int maxTotal = 8;
    //Maximum wait timeout
    private long maxWaitMillis = -1;
    //Open test
    private boolean testOnBorrow = false;
    ...ellipsis get,set...
}

Step 2: create Redis auto configuration class and register JedisPool connection pool object

@Configuration
//If there's jedis Class creates a Bean
@ConditionalOnClass({Jedis.class,JedisPoolConfig.class})
//If you haven't already created Jedis, create it
@ConditionalOnMissingBean(Jedis.class)
//@EnableConfigurationProperties: enables RedisProperties
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {

    @Bean
    public JedisPool jedisPool(RedisProperties redisProperties){
        JedisPoolConfig config = new JedisPoolConfig();
        //Maximum number of free connections
        config.setMaxIdle(redisProperties.getMaxIdle());
        //Maximum number of linked objects
        config.setMaxTotal(redisProperties.getMaxTotal());
        //Link timeout
        config.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
        //Get the connection is to test whether the connection is unblocked
        config.setTestOnBorrow(redisProperties.isTestOnBorrow());
        //Parameters: configuration object, redis host address, timeout, password
        return new JedisPool(config,redisProperties.getHost(),redisProperties.getPort(),redisProperties.getTimeout(),redisProperties.getPassword());
    }

    @Bean
    public RedisTemplate redisTemplate(JedisPool jedisPool){
        return new RedisTemplate(jedisPool);
    }
}

2.3. Create RedisTemplate

Create RedisTemplate, which is a tool class used to operate Redis. The code is as follows

public class RedisTemplate {

    //Connection pool
    private JedisPool jedisPool;

    public RedisTemplate(JedisPool jedisPool){
        this.jedisPool = jedisPool;
    }
    public RedisTemplate(){}


    public Jedis getJedis(){
        return jedisPool.getResource();
    }
    //Save string
    public String set(String key ,String value){
        Jedis jedis = getJedis();
        String result = jedis.set(key  , value);
        jedis.close();
        return result;
    }
    //Get string
    public String get(String key){
        Jedis jedis = getJedis();
        String result = jedis.get(key);
        jedis.close();
        return result;
    }

}

2.4. Create spring factories

Create resources \ meta-inf \ spring Factories file, add the name of the configuration class

org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.whale.config.RedisAutoConfiguration

2.5. Package start

Using terminal, execute mvn install to package the factory to the local warehouse

Here, start development is completed. The next step is in the project POM The start (SpringBoot starter redis) is introduced into XML. When the project starts, the SpringBoot automatic configuration process will load SpringBoot starter redis / mate-inf / Spring RedisAutoConfiguration in factories, JedisPool and RedisTemplate will be registered in the Spring container. The rest is to inject RedisTemplate interface into the project.

The project structure is as follows

3. Use Starter

3.1.pom import dependency

Here we will find the starter project of install above

<dependency>
    <groupId>cn.whale</groupId>
    <artifactId>springboot-starter-redis</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

3.2. Configure Redis

This configuration item corresponds to RedisProperties in springboot starter redis. If it is not configured, the default value will be used

spring:
  redis:
    password: 123456
    host: 127.0.0.1
    port: 6379

3.3. Write controller

Inject RedisTemplate into the controller to demonstrate the set and get methods

@RestController
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/redis/set/{key}/{value}")
    public String redisSet(@PathVariable("key")String key , @PathVariable("value")String value){
        return redisTemplate.set(key,value);
    }
    @RequestMapping("/redis/get/{key}")
    public String redisGet(@PathVariable("key")String key){
        return redisTemplate.get(key);
    }

}

3.4. Start test

Start the project and access the path for testing. The results are as follows:

Test get

Here are the effects in Redis

You might ask, what's the use of defining a starter? In fact, it is more useful. For example, we need to develop a general component and package a jar. This component needs to be dependent on multiple projects. How can we do some initialization configuration when the program starts? Defining a starter is a good way.

The article is over. If the article is helpful to you, please give it a good comment, please give it a good comment, please give it a good comment

Keywords: Java Spring Spring Boot

Added by skippa on Thu, 13 Jan 2022 15:10:56 +0200