The introduction

articleSpringBoot Every Day, Its Automatic assembly principle can not tellWe have saidspringBootHow to achieve automatic assembly (recommended to see the next article, because the relationship between the before and after), this article if we ourselves to implement oneSpringBootthestarter. Without further ado, let’s cut to the chase.What is theSpring Boot Starter? Let’s take a look at the official website.

Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa dependency in your project.

Nani, a lot of English, is that interesting to read on? Did you see this straight out of the. We’re at the door. Why don’t you come in and have a cup of tea? You can see this or keep reading. Instead of explaining what this paragraph means, let’s look at what the starter has solved for us. Let’s use the example from the website above to illustrate that we need to adapt JPA in Spring to operate the database. Before there is a SpringBoot-starter, we need to introduce jPA steps

  • throughmavenIntroduce JDBC dependencies, as well as jPA-related dependencies
  • writejpaRelated configuration files
  • All kinds of online queries to find information for debugging, debugging process for beginners may be a bit of a crash and encounter all kinds of weird problems,jarBag conflict, thisjarThe package can’t be downloaded. It’s missing somethingjarThe package.
  • Finally, after going through a lot of hardships and solving various problems, I finally got the project running, and then integrated the projectjpaThe problems encountered, as well as the steps of integration, are documented in detail. Convenient next time in need of integrationjpaWhen you go straight tocopyIt’ll be ok. We didn’t have it beforestarterI wonder if this is how it used to be. The drawbacks are obvious, such as the complexity of the process, the constant need to paste and copy (which is what programmers do all the time, and don’t care if it’s an extra time or two), the difficulty and inefficiency of integrating other components into your project. And that’s what happens996More programmers (can’t go back at night69A).

The SpringBoot Starter appears

We can look at itSpringBootWhat are they offering us nowstarterI have a screenshot herestarterAnd more, please click https://github.com/spring-projects/spring-boot/tree/master/spring-boot-project/spring-boot-startersstarterImplementation: Although we each component ofstarterImplementations vary, but they all use basically the same two things:ConfigurationPropertiesandAutoConfiguration. becauseSpring BootAdvocate”Convention over configuration“So we usedConfigurationPropertiesTo save our configurations, and these configurations can all have a default value that takes effect if we do not actively override the original configuration. In addition to that,startertheConfigurationPropertiesIt also allows all configuration properties to be aggregated into one file (usually inresourcesIn the directoryapplication.properties), and then we said goodbyeSpringIn the projectXMLHell.starterThe emergence of a variety of complex configuration helped us to encapsulate, so that we can really reach out of the box. Not only does it lower the threshold for us to use it, but it also greatly improves our development efficiency. As I said earlierSpringBoot AutowiringSo we can spend more time with our girlfriends.

Implement your own SpringBoot Starter

Naming conventions

If you’re going to have a baby, the first thing you need before birth is a name. The child’s name is a sign of your blood and that of your lover. It will not take the name of the old Wang next door, which will certainly attract strange eyes. In Maven, groupId stands for last name and artifactId for first name. Spring Boot also has a naming suggestion. So names are not to be given casually, but to be given according to official advice.

What’s in a name All official starters follow a similar naming pattern; spring-boot-starter-*, where * is a particular type of application. This naming structure is intended to help when you need to find a starter. The Maven integration in many IDEs lets you search dependencies by name. For example, with the appropriate Eclipse or STS plugin installed, You can press Ctrl-space in the POM Editor and type “spring-boot-starter” for a complete list. As explained in the Third party starters should not start with spring-boot, as it is reserved for official Spring Boot artifacts. Rather, a third-party starter typically starts with the name of the project. For example, a third-party starter project called thirdpartyproject would typically be named thirdpartyproject-spring-boot-starter.

The official starter naming format is spring-boot-starter-{XXXX}. For example, the third party naming format is spring-boot-starter- activemQ } {XXXX – spring – the boot – the starter. Such as mybatis – spring – the boot – the starter. If we ignore this convention, isn’t it less “professional” than what we write?

Customize a Starter

Let’s implement a custom SMS sending starter, named SMS-spring-boot-starter.

  1. The introduction ofpom
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
 <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-configuration-processor</artifactId>  <optional>true</optional>  </dependency>  <dependency>  <groupId>org.projectlombok</groupId>  <artifactId>lombok</artifactId>  <version>1.16.18</version>  <scope>provided</scope>  </dependency> Copy the code
  1. Writing a configuration file

When sending SMS messages, we need to configure some account information. Different SMS providers have different account information, so we need to define an XXXXProperties to automatically assemble these account information. Let’s take Tencent Cloud and Alibaba Cloud as an example;

@ConfigurationProperties(prefix = "sms")
@Data
public class SmsProperties {

    private SmsMessage aliyun = new SmsMessage();
  private SmsMessage tencent = new SmsMessage();   @Data  public static class SmsMessage{    / * ** user name* /  private String userName;   / * ** password* /  private String passWord;   / * ** the secret key* /  private String sign;   / * * * * /  private String url;   @Override  public String toString(a) {  return "SmsMessage{" +  "userName='" + userName + '\' ' +  ", passWord='" + passWord + '\' ' +  ", sign='" + sign + '\' ' +  ", url='" + url + '\' ' +  '} ';  }  } } Copy the code

If you want to use the SmsProperties for other projects, you only need to configure the SmsProperties in the configuration file (application.yml). Such as:

sms:
  aliyun:
    pass-word: 12345
User - name: Java financialSign: ali cloud url: http://aliyun.com/send  tencent:  pass-word: 6666 User - name: Java financialSign: tencent cloud url: http://tencent.com/send Copy the code

remember@ConfigurationPropertiesIs there one in the notesprefixProperty, the property that we configured issmsThe main purpose of this configuration is to distinguish the parameters of each component. Now, there’s a little bit of awareness here when we’re typing in the configuration filesmsourideaIt’s going to prompt thatsmsWhat attributes can be configured, and the comments for each attribute are marked. It is recommended that the comments be written in English, so that you will appear more professional.The hint is to introduce the followingjar.

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

The introduction of thejarAfter that, when we compile it, it will be inMETA-INFCreate one under the folderspring-configuration-metadata.jsonThe file.We can see that this file is actually generated based on the member properties of the SmsProperties class.

  1. Then in writing SMS autoconfiguration class:
@EnableConfigurationProperties(value = SmsProperties.class)
@Configuration
public class SmsAutoConfiguration  {
    / * ** Ali Cloud send SMS implementation class * @param smsProperties  * @return * /  @Bean  public AliyunSmsSenderImpl aliYunSmsSender(SmsProperties smsProperties){  return new AliyunSmsSenderImpl(smsProperties.getAliyun());  }  / * ** Tencent Cloud sending SMS implementation class * @param smsProperties  * @return * /  @Bean  public TencentSmsSenderImpl tencentSmsSender(SmsProperties smsProperties){  return new TencentSmsSenderImpl(smsProperties.getTencent());  } } Copy the code

Write our SMS implementation class:

public class AliyunSmsSenderImpl implements SmsSender {

    private SmsMessage smsMessage;

    public AliyunSmsSenderImpl(SmsMessage smsProperties) {
 this.smsMessage = smsProperties;  }   @Override  public boolean send(String message) {  System.out.println(smsMessage.toString()+"Start sending SMS ==" Message content:"+message);  return true;  } } Copy the code
  1. Let the starter to take effect

Starter integrates applications in two ways:

  • Passive effect let’s first look at the familiar way bySpringBoottheSPITo load our starter. We need to be able toMETA-INFLet’s make a new onespring.factoriesfilekeyforOrg. Springframework. Boot. Autoconfigure. EnableAutoConfiguration, valueIt is ourSmsAutoConfigurationFully qualified name (Remember to remove the space before and after, otherwise it will not take effect).
  • Active effect instarterComponents integrated into ourSpring BootThis function must be enabled when the application is executedstarterTo take effect, you can customize one@EnableThe annotations then put the autoconfiguration class throughImportAnnotations come in.
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({SmsAutoConfiguration.class})
public @interface EnableSms {
} Copy the code

To use this annotation, enable it on the startup class. 5.Package and deploy to the warehouseIf it’s local, go straight throughmvn installA command will do. If you need to deploy to your company’s warehouse, this is not necessary. 6.Let’s make a new oneSpringBootProject introduction we just wrotestarter

 <dependency>
            <groupId>com.workit.sms</groupId>
            <artifactId>sms-spring-boot-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
      </dependency>
Copy the code

Configure the SMS account information in the project configuration fileThe test code

@SpringBootApplication
@EnableSms
public class AutoconfigApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(AutoconfigApplication.class, args);
 AliyunSmsSenderImpl aliyunSmsSender = applicationContext.getBean(AliyunSmsSenderImpl.class);  aliyunSmsSender.send("Sending text messages on Aliyun");  TencentSmsSenderImpl tencentSmsSender = applicationContext.getBean(TencentSmsSenderImpl.class);  tencentSmsSender.send("Sending text messages with Tencent Cloud");  } Copy the code

Running result:

SmsMessage{userName='Java financial', passWord='12345', sign='Ali Yun', url='http://aliyun.com/send'} Start sending SMS == "SMS content: send SMS with AliyunSmsMessage{userName='Java financial', passWord='6666', sign='Tencent Cloud', url='http://tencent.com/send'} Start sending SMS == "SMS content: Send SMS with Tencent CloudCopy the code

So far we have a custom starter has been completed, the starter is just a demo demo, the code is a little rough, the project structure is also a bit of a problem. Just focus on how this works. Start creating your own starter.

conclusion

  • SpringBoot starter, made it easy to integrate other components into our project. It gives simplicity to others and complexity to itself. The idea of “sacrifice the self to achieve the greater self” is still worth learning. In our daily work, such as the development of a component, or a tool class, we should try to make the user can do the brainless use, do not make it too complex, but also let the user can flexibly expand.

The end of the

  • Due to their lack of knowledge, it is hard to avoid mistakes, if you find the wrong place, also hope to leave a message to me to point out, I will correct it.
  • If you think the article is good, your retweet, share, praise, like, comment is the biggest encouragement to me.
  • Thank you for reading. I very much welcome and thank you for your attention.Standing on the shoulders of giants pick apples: https://www.cnblogs.com/tjudzj/p/8758391.html https://blog.springlearn.cn/posts/14644/