Introduction and use of Spring Boot Starter

catalogue

Spring Boot Starter project creation

Automatically create client

Using Starter

Enable Starter auto build with annotations

Enable Starter auto build using configuration

Configure Starter content tips

The convenience of Spring Boot is that it simplifies many cumbersome configurations, which is a blessing for developers. By introducing various Spring Boot Starter packages, you can quickly build a project scaffold.

The Spring Boot Starter package currently available includes:

  • Spring boot starter Web: quickly build a web project based on Spring mvc# and use Tomcat as the default embedded container.
  • Spring boot starter data Redis: Redis operation.
  • Spring boot starter data Mongodb: operate Mongodb.
  • Spring boot starter data JPA: operate Mysql.
  • Spring boot starter Activemq: operate Activemq.
  • ......


Automatic configuration is very convenient. When we want to operate Mongodb, we only need to introduce the dependency of spring boot Starter data Mongodb, and then configure the link information of Mongodb data. Mongodb. If URI = Mongodb: / / localhost/test, you can use MongoTemplate to operate data. The initialization of MongoTemplate is left to Starter.

The trouble with automatic configuration is that when an error occurs, it becomes more difficult to troubleshoot the problem. The logic of automatic configuration is in Spring Boot Starter. To quickly locate the problem, you must understand the internal principle of Spring Boot Starter. Next, let's implement a Spring Boot Starter by ourselves.

Spring Boot Starter project creation

Create a project spring boot starter demo, POM The XML configuration code is shown below.

<dependencies>
    <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>
</dependencies>

Create a configuration class for configuring values in the property file, which is equivalent to spring data. Mongo in this form, the code is as follows.

 
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
@Data
@ConfigurationProperties("spring.user")
public class UserPorperties {
    private String name;
}

Define a Client, which is equivalent to MongoTemplate, and specify a method to obtain the value in the configuration. The code is as follows.

public class UserClient {
    private UserPorperties userPorperties;
    public UserClient() {
    }
    public UserClient(UserPorperties p) {
        this.userPorperties = p;
    }
    public String getName() {
        return userPorperties.getName();
    }
}

Automatically create client

A basic Starter package has been defined, but the UserClient cannot be used at present, because we do not automatically build an instance of the UserClient. Next, start building the UserClient, as shown below.

@Configuration
@EnableConfigurationProperties(UserPorperties.class)
public class UserAutoConfigure {
    @Bean
    @ConditionalOnProperty(prefix = "spring.user", value = "enabled", havingValue = "true")
    public UserClient userClient(UserPorperties userPorperties) {
        return new UserClient(userPorperties);
    }
}

Spring Boot will scan the packages at the same level as the startup class by default. If our Starter and startup class are not in the same main package, how can UserAutoConfigure take effect?

Create a META-INF folder under resources, and then create a spring. Inf folder in the META-INF folder Factories file, which specifies the automatically configured classes:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.cxytiandi.demo.UserAutoConfigure

When Spring Boot starts, it will read spring Factories file, and then activate the corresponding configuration class according to the configuration. So far, a simple Starter package is implemented.

Using Starter

Now you can introduce this Starter package into other projects. The code is as follows.

<dependency>
<groupId>com.cxytiandi</groupId>
<artifactId>spring-boot-starter-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>

After importing, you can directly use UserClient. UserClient has been initialized automatically when the project is started. The code is as follows.

@RestController
public class UserController {

@Autowired
private UserClient userClient;

@GetMapping("/user/name")
public String getUserName() {
return userClient.getName();
}
}

Configure the value of name in the properties file and open UserClient:

spring.user.name=zhangsan
spring.user.enabled=true

Visit / user/name to return the zhangsan configured by us.

Enable Starter auto build with annotations

In many cases, we don't want to execute the initialization logic when introducing the Starter package. Instead, we want the user to specify whether to enable the automatic configuration function of the Starter package. For example, the commonly used @ EnableAsync annotation is used to enable the asynchronous execution of calling methods.

Similarly, we can also enable automatic configuration through annotation. If annotation is used, spring There is no need to write factories. Let's see how to define the annotation to enable automatic configuration. The code is as follows.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({UserAutoConfigure.class})
public @interface EnableUserClient {

}

The core of this code is @ Import ({UserAutoConfigure.class}). By importing, the UserAutoConfigure instance is added to the SpringIOC container, so that automatic configuration can be started.

The way to use it is to add this annotation to the startup class. The code is as follows.

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

Turn on Starter auto build using configuration

In some scenarios, multiple objects will be configured in UserAutoConfigure. For these objects, if you don't want to configure them all, or want the user to specify that you need to start the configuration before building the objects, we can specify whether to start the configuration function through @ ConditionalOnProperty. The code is as follows.

@Bean
@ConditionalOnProperty(prefix = "spring.user",value = "enabled",havingValue = "true")
public UserClient userClient(UserPorperties userPorperties) {
return new UserClient(userPorperties);
}

Through the above configuration, only when @ EnableUserClient is added to the startup class and spring.com is in the configuration file user. UserClient will be automatically configured only when enabled = true.

Configure Starter content tips

In the process of customizing the Starter package, another important point is to prompt the configured content items. It should be noted that prompts are not supported in Eclipse, but can be prompted in Spring Tools 4 for Eclipse.

To define the prompt content, you need to create a spring-configuration-metadata JSON file, the code is as follows.

{ "properties": [ { "name": "spring.user.name", "defaultValue": "cxytinadi" }, { "name": "spring.user.enabled", "type": "java.lang.Boolean", "defaultValue": false } ] }
  • Name: configuration name
  • Type: configured data type
  • defaultValue: default value

The previous article "spring cloud super introduction" Spring Boot project construction steps (super detailed) "6"

The next article introduces what Spring Cloud Eureka is 

Recommendation of relevant springboot actual combat projects
Design and implementation of epidemic prevention system based on java ssm springboot+VUE

Design and implementation of front and back office of film ticketing website management system based on java springboot+mybatis

Design and implementation of spring boot + mybatis winery internal management system based on Java SSM

Design and implementation of smart life sharing platform based on JAVA springboot+mybatis

Design and implementation of furniture mall platform based on Java springboot+vue+redis

Design and implementation of anti epidemic substance information management system based on JAVA SSM springboot

View more home page practical projects > > >

Keywords: Java Spring Boot Spring Cloud

Added by po on Mon, 24 Jan 2022 00:05:55 +0200