如何创建自定义 Spring Boot Starter

x33g5p2x  于2022-09-28 转载在 Spring  
字(8.2k)|赞(0)|评价(0)|浏览(693)

在本教程中,我们将学习如何创建自定义的 Spring Boot Starter。 Spring Boot 启动器使开发更容易和快速。大多数常见任务都有几个内置的启动器,但是您也可以创建自己的启动器,以便在您的应用程序中重用某些功能。

我们基本的 Spring Boot starter 将使用 ascii 艺术打印一个文本字符串。我们将其命名为 spring-boot-starter-

Spring Boot 框架中,所有启动器都遵循类似的命名模式:spring-boot-starter-*,其中 * 表示特定类型的应用程序。例如,如果我们想使用 Spring 和 JPA 进行数据库访问,我们需要在项目的 pom.xml 文件中包含 spring-boot-starter-data-jpa 依赖项。

让我们从 pom.xml 文件开始:

<project xmlns="http://maven.apache.org/POM/4.0.0" 	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 	<modelVersion>4.0.0</modelVersion>  	<groupId>com.masterspringboot</groupId> 	<artifactId>spring-boot-starter-banner-service</artifactId> 	<version>1.0.0</version> 	<packaging>jar</packaging>  	<name>my-org-starter-security</name> 	<url>http://maven.apache.org</url>  	<properties> 		<java.version>1.8</java.version> 		<maven.compiler.source>1.8</maven.compiler.source> 		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 		<maven.compiler.target>1.8</maven.compiler.target> 		<spring.boot.version>2.1.9.RELEASE</spring.boot.version> 		<spring.framework.version>5.2.1.RELEASE</spring.framework.version> 	</properties>  	<dependencies> 		<dependency> 			<groupId>org.springframework.boot</groupId> 			<artifactId>spring-boot-starter</artifactId> 			<version>${spring.boot.version}</version> 			<scope>compile</scope> 		</dependency> 		<dependency> 			<groupId>org.springframework.boot</groupId> 			<artifactId>spring-boot-autoconfigure</artifactId> 			<version>${spring.boot.version}</version> 		</dependency>  		<dependency> 			<groupId>org.springframework.boot</groupId> 			<artifactId>spring-boot-configuration-processor</artifactId> 			<version>${spring.boot.version}</version> 			<optional>true</optional> 		</dependency>  	</dependencies>  	<build> 		<plugins> 			<plugin> 				<groupId>org.apache.maven.plugins</groupId> 				<artifactId>maven-jar-plugin</artifactId> 				<version>3.1.2</version> 				<configuration> 					<archive> 						<addMavenDescriptor>false</addMavenDescriptor> 						<manifest> 							<addDefaultImplementationEntries>false</addDefaultImplementationEntries> 							<addDefaultSpecificationEntries>false</addDefaultSpecificationEntries> 						</manifest> 					</archive> 				</configuration> 			</plugin> 		</plugins> 	</build> </project>

由于此启动器将使用自动配置功能,因此我们将其依赖项添加到主要的 spring-boot-starter 中。

这是 AutoConfiguration 类:

package com.masterspringboot.config;

import com.masterspringboot.service.MyBannerService;
import com.masterspringboot.service.MyBannerServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration @ConditionalOnClass(MyBannerService.class) @EnableConfigurationProperties(MyBannerProperties.class)

public class MyBannerAutoConfiguration {
  @Autowired private MyBannerProperties greeterProperties;

  //conditional bean creation     

  @Bean @ConditionalOnMissingBean public MyBannerService helloService() {
    return new MyBannerServiceImpl(greeterProperties);
  }
}

此类负责使用从 MyBannerProperties 注入的属性创建“MyBannerService”。

@ConditionalOnMissingBean 注释仅用于在缺少给定 bean 时加载 bean。

仅当上下文中不存在此类型的其他 bean 时,上述 bean 才会由 Spring 加载。另一方面,如果应用程序上下文中已经存在“MyBannerService”类型的 bean,则不会创建上述 bean。

然后,在 MyBannerProperties 类中,我们只编写了以下属性来自定义横幅的大小和字体:

package com.masterspringboot.config;

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

@ConfigurationProperties(prefix = "mybanner")
public class MyBannerProperties {
  String fontName;
  int fontSize;

  public String getFontName() {
    return fontName;
  }

  public void setFontName(String fontName) {
    this.fontName = fontName;
  }

  public int getFontSize() {
    return fontSize;
  }

  public void setFontSize(int fontSize) {
    this.fontSize = fontSize;
  }
}

实际实现包含在 MyBannerServiceImpl 中,它在底层使用 java.awt 创建一个 BufferedImage,然后在其中渲染一个文本:

package com.masterspringboot.service;

import com.masterspringboot.config.MyBannerProperties;
import java.awt.*;
import java.awt.image.BufferedImage;

public class MyBannerServiceImpl implements MyBannerService {
  MyBannerProperties properties;

  public MyBannerServiceImpl(MyBannerProperties greeterProperties) {
    this.properties = greeterProperties;
  }

  @Override
  public void hello(String text) {
    int width = 100;
    int height = 30;
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();
    g.setFont(new Font(properties.getFontName(), Font.BOLD, properties.getFontSize()));
    Graphics2D graphics = (Graphics2D) g;
    graphics.setRenderingHint(
        RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    graphics.drawString(text, 10, 20);
    for (int y = 0; y < height; y++) {
      StringBuilder sb = new StringBuilder();
      for (int x = 0; x < width; x++) {
        sb.append(image.getRGB(x, y) == -16777216 ? " " : "$");
      }
      if (sb.toString().trim().isEmpty()) {
        continue;
      }
      System.out.println(sb);
    }
  }
}

最后,这个服务的接口是:

package com.masterspringboot.service;

public interface MyBannerService {
  void hello(String text);
}

我们完成了 Starter 代码。 Spring Boot 如何加载这个自动配置类?为了使用自动配置的强大功能,您需要在 META-INF/spring.factories 文件中创建它。您指定包含自动配置的类:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.masterspringboot.config.MyBannerAutoConfiguration

就这样。构建启动器:

$ mvn install

在 Spring Boot 应用程序中使用自定义启动器

要在您的应用程序中使用自定义的 Spring Boot Starter,解决其依赖关系就足够了:

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	
   <modelVersion>4.0.0</modelVersion>
    	
   <parent>
       		
      <groupId>org.springframework.boot</groupId>
       		
      <artifactId>spring-boot-starter-parent</artifactId>
       		
      <version>2.1.9.RELEASE</version>
       		
      <relativePath/>
       
      <!-- lookup parent from repository -->
       	
   </parent>
    	
   <artifactId>demo-app</artifactId>
    	
   <name>my-demo-app</name>
    	
   <description>Demo project for Spring Boot</description>
     	
   <properties>
       		
      <java.version>1.8</java.version>
       	
   </properties>
     	
   <dependencies>
       		
      <dependency>
          			
         <groupId>com.masterspringboot</groupId>
          			
         <artifactId>spring-boot-starter-banner-service</artifactId>
          			
         <version>1.0.0</version>
          		
      </dependency>
       	
   </dependencies>
     	
   <build>
       		
      <plugins>
          			
         <plugin>
             				
            <groupId>org.springframework.boot</groupId>
             				
            <artifactId>spring-boot-maven-plugin</artifactId>
             			
         </plugin>
          		
      </plugins>
       	
   </build>
    
</project>

这是主要的应用程序类:

package com.masterspringboot;

import com.masterspringboot.service.MyBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CustomApplicationStarter implements CommandLineRunner {
  @Autowired MyBannerService service;

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

  @Override
  public void run(String... strings) throws Exception {
    service.hello("Hello");
  }
}

我们的 application.properties 将设置大小和字体名称如下:

mybanner.fontSize=16 mybanner.fontName=SansSerif

如果你运行它,你会看到一个漂亮的 ascii 文本横幅在运行:

$ mvn install spring-boot:run     2021-01-30 16:09:00.741  INFO 30241 --- [           main] c.m.CustomApplicationStarter             : Started CustomApplicationStarter in 0.758 seconds (JVM running for 4.136)            $$   $$             $$ $$                                                                    $$   $$             $$ $$                                                                    $$   $$             $$ $$                                                                    $$   $$   $$$$   $$ $$  $$$$                                                           $$   $$  $$$$$  $$ $$ $$$$$                                                          $$$$$$ $$$$$  $$ $$$$$$$$                                                         $$$$$$ $$$$$$ $$ $$$$   $$                                                         $$   $$ $$$$$$ $$ $$$$   $$                                                         $$   $$ $$        $$ $$$$   $$                                                         $$   $$ $$$$$  $$ $$$$$$$$                                                         $$   $$  $$$$$  $$ $$ $$$$$                                                          $$   $$   $$$$  $$ $$  $$$$

而已。我们刚刚介绍了如何开发自定义 Spring Boot Starter 的基本示例。

您可以在此处找到自定义 Spring Boot 启动器和演示应用程序:https://github.com/fmarchioni/masterspringboot/tree/master/starters

相关文章

微信公众号

最新文章

更多