Custom creation of springBoot starter

foreword

Usually we always write some non-business-related public codes in our work. These public codes are usually placed in a module separately. When using springBoot for development, the spring team provides us with many out-of-the-box starters. Then How to create your own starter to encapsulate these public non-business codes

Create starter submodule

First look at the structure of the project
insert image description here

Let's start creating our demo-spring-boot-starter

1. Create properties attribute entity

@ConfigurationProperties(prefix = "spring.demo")
public class DemoProperties {
    
    
	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;
	}
}

2. Create service

public class DemoService {
    
    
	private final DemoProperties demoProperties;

	public DemoService(DemoProperties demoProperties) {
    
    
		this.demoProperties = demoProperties;
	}
	public void test(){
    
    
		System.out.println(this.demoProperties.getName() +"-"+this.demoProperties.getAge());
	}
}

3. Create autoConfig

@Configuration
@ConditionalOnClass(DemoProperties.class)
@EnableConfigurationProperties(DemoProperties.class)
public class DemoAutoConfiguration {
    
    
	private DemoProperties demoProperties;

	@Bean
	@ConditionalOnMissingBean
	public DemoService demoService(){
    
    
		return new DemoService(demoProperties);
	}
}

Here is a brief introduction to the use of several conditional annotations

  • @ConditionalOnBean //This bean will only be created when the bean is required to exist
  • @ConditionalOnMissingBean //This bean will only be created when the bean does not exist
  • @ConditionalOnClass //This bean will only be created when the class exists
  • @ConditionalOnMissingClass //The bean will only be created when the class does not exist.
    These conditional annotations can control the timing of bean injection, so that when a third party introduces our dependencies, an exception will be thrown because there is no bean or class. After
    that , and annotations such as @DependsOn can control the injection order of beans;

4. Create spring.factories and expose autoConfig

After creating the META-INF folder under the resources folder, create spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration= \
    com.demo.config.DemoAutoConfiguration

At this point, a custom starter has been created, and then it can be packaged into a jar and used happily.

Guess you like

Origin blog.csdn.net/csdn_tiger1993/article/details/126066344