当前位置: 首页 > news >正文

springboot常用扩展点

当涉及到Spring Boot的扩展和自定义时,Spring Boot提供了一些扩展点,使开发人员可以根据自己的需求轻松地扩展和定制Spring Boot的行为。本篇博客将介绍几个常用的Spring Boot扩展点,并提供相应的代码示例。

1. 自定义Starter(面试常问)

Spring Boot通过Starter来提供自动配置和依赖管理的功能。我们可以创建自己的Starter来打包和共享自定义组件。下面是一个简单的自定义Starter示例:

首先,创建一个Maven项目,并在pom.xml中添加以下依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>2.6.1</version>
</dependency>

然后,创建一个自动配置类,命名为CustomAutoConfiguration,并添加@Configuration@EnableConfigurationProperties注解:

@Configuration
@EnableConfigurationProperties(CustomProperties.class)
public class CustomAutoConfiguration {// 自定义自动配置逻辑
}

接下来,创建一个自定义属性类CustomProperties,用于配置自定义属性:

@ConfigurationProperties("custom")
public class CustomProperties {private String message;// getter和setter方法省略
}

最后,在src/main/resources/META-INF/spring.factories文件中添加自动配置类的引用:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.CustomAutoConfiguration

现在,我们就可以将项目打包成一个jar文件,供其他项目使用,并通过配置文件进行自定义属性的配置。

2. 自定义条件注解

Spring Boot提供了多种条件注解,如@ConditionalOnProperty@ConditionalOnClass等。这些注解在springboot框架中非常重要,包括springboot 的灵活性离不开条件注解。当然我们也可以自定义条件注解来根据特定条件决定是否生效。以下是一个示例:

首先,创建一个自定义条件注解@EnableCustomFeature

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(CustomFeatureCondition.class)
public @interface EnableCustomFeature {String value();
}

然后,创建一个自定义条件类CustomFeatureCondition,实现Condition接口:

public class CustomFeatureCondition implements Condition {@Overridepublic boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {String propertyValue = context.getEnvironment().getProperty("custom.feature.enabled");return "true".equalsIgnoreCase(propertyValue);}
}

接下来,在使用自定义条件注解的类上添加注解@EnableCustomFeature

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

最后,根据配置文件中的属性custom.feature.enabled的值决定是否启用自定义功能。

3. 自定义事件监听器

Spring Boot的事件模型允许我们监听和响应应用程序中发生的事件,这也是springboot的核心的一部分。我们可以创建自定义事件监听器,以便在特定事件发生时执行自定义逻辑。以下是一个示例:

首先,定义一个自定义事件类CustomEvent

public class CustomEvent extends ApplicationEvent {public CustomEvent(Object source) {super(source);}
}

然后,创建一个自定义事件监听器CustomEventListener,实现ApplicationListener接口:

@Component
public class CustomEventListener implements ApplicationListener<CustomEvent> {@Overridepublic void onApplicationEvent(CustomEvent event) {// 执行自定义逻辑System.out.println("Custom event received: " + event.getSource());}
}

最后,在适当的地方触发自定义事件:

@Component
public class MyComponent {private final ApplicationEventPublisher eventPublisher;public MyComponent(ApplicationEventPublisher eventPublisher) {this.eventPublisher = eventPublisher;}public void doSomething() {// 触发自定义事件eventPublisher.publishEvent(new CustomEvent(this));}
}

以上示例中,CustomEventListener监听并处理CustomEvent事件,当事件触发时执行自定义逻辑。

4. 自定义启动器监听器

Spring Boot的启动器监听器(ApplicationRunner和CommandLineRunner)允许我们在应用程序启动后执行一些自定义逻辑。我们可以创建自己的启动器监听器来执行特定的初始化或后续操作。以下是一个示例:

@Component
public class CustomApplicationRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) throws Exception {// 在应用程序启动后执行自定义逻辑System.out.println("Custom application runner executed");}
}

CustomApplicationRunner实现了ApplicationRunner接口,并在run方法中定义了自定义逻辑。当应用程序启动后,该逻辑将被执行。

5. CommandLineRunner和ApplicationRunner

CommandLineRunnerApplicationRunner接口允许我们在Spring Boot应用程序启动后执行一些自定义逻辑。这些接口的实现类将在应用程序上下文加载完成后自动调用。它们可以用于执行一些初始化操作、数据加载、调度任务等。下面是一个示例:

@Component
public class MyCommandLineRunner implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {// 在应用程序启动后执行自定义逻辑System.out.println("Command line runner executed");}
}

在这个示例中,MyCommandLineRunner实现了CommandLineRunner接口,并在run方法中定义了自定义逻辑。当应用程序启动后,该逻辑将被执行。

6. WebMvcConfigurer

WebMvcConfigurer接口允许我们自定义和配置Spring MVC的行为。通过实现该接口,我们可以添加拦截器、自定义消息转换器、配置视图解析器等。以下是一个示例:

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {// 添加自定义拦截器registry.addInterceptor(new CustomInterceptor());}@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {// 添加自定义消息转换器converters.add(new CustomMessageConverter());}@Overridepublic void configureViewResolvers(ViewResolverRegistry registry) {// 配置自定义视图解析器registry.jsp("/WEB-INF/views/", ".jsp");}
}

在上述示例中,MyWebMvcConfigurer实现了WebMvcConfigurer接口,并重写了一些方法来添加拦截器、消息转换器和视图解析器。

7. ErrorController

ErrorController接口允许我们自定义处理应用程序中的错误和异常。通过实现该接口,我们可以自定义错误处理逻辑,例如在出现错误时返回自定义错误页面或响应。以下是一个示例:

@Controller
public class MyErrorController implements ErrorController {@RequestMapping("/error")public String handleError() {// 自定义错误处理逻辑return "error";}@Overridepublic String getErrorPath() {return "/error";}
}

在这个示例中,MyErrorController实现了ErrorController接口,并在handleError方法中定义了自定义错误处理逻辑。当应用程序出现错误时,将调用该方法进行处理。

以上是常用的Spring Boot扩展点的一部分。通过自定义Starter、自定义条件注解和事件发布机制d等扩展接口,我们可以灵活地扩展和定制Spring Boot应用程序的功能和行为,以满足特定的需求。

希望这篇博客对于刚接触Spring Boot的小伙伴有所帮助。如果您有任何进一步的问题,请随时提问(ps:后面还会对该篇文章更新,还有很多扩展的地方)。https://editor.csdn.net/md?not_checkout=1&spm=1001.2100.3001.4503&articleId=135513767

http://www.lryc.cn/news/277581.html

相关文章:

  • 19道ElasticSearch面试题(很全)
  • 向爬虫而生---Redis 拓宽篇3 <GEO模块>
  • Vue项目里实现json对象转formData数据
  • leetcode刷题记录
  • SpringMVC通用后台管理系统源码
  • 深度解析Dubbo的基本应用与高级应用:负载均衡、服务超时、集群容错、服务降级、本地存根、本地伪装、参数回调等关键技术详解
  • 备战2024美赛数学建模,文末获取历史优秀论文
  • Java加密解密大全(MD5、RSA)
  • C语言程序设计考试掌握这些题妥妥拿绩点(写给即将C语言考试的小猿猴们)
  • 编译ZLMediaKit(win10+msvc2019_x64)
  • JS-基础语法(一)
  • 18款Visual Studio实用插件(更新)
  • 三、java线性表(顺序表、链表、栈、队列)
  • PiflowX-MysqlCdc组件
  • 2023春季李宏毅机器学习笔记 03 :机器如何生成文句
  • dplayer播放hls格式视频并自动开始播放
  • 使用Vivado Design Suite平台板、将IP目录与平台板流一起使用
  • PACS医学影像报告管理系统源码带CT三维后处理技术
  • 介绍几种常见的质数筛选法
  • Qt/QML编程学习之心得:Linux下读写GPIO(23)
  • Unity中URP下深度图的线性转化
  • Low Poly Cartoon House Interiors
  • [算法与数据结构][c++]:左值、右值、左值引用、右值引用和std::move()
  • 【QT】day3
  • c++ fork, execl 参数 logcat | grep
  • QT:单例
  • IPv6路由协议---IPv6动态路由(OSPFv3-4)
  • 移动通信原理与关键技术学习(4)
  • 第二百五十八回
  • freesurfer-reconall后批量提取TIV(颅内总体积)