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 {
    @Override
    public 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> {
    @Override
    public 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 {
    @Override
    public 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 {
    @Override
    public 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 {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加自定义拦截器
        registry.addInterceptor(new CustomInterceptor());
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 添加自定义消息转换器
        converters.add(new CustomMessageConverter());
    }

    @Override
    public 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";
    }

    @Override
    public 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

  • 28
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
登录(Single Sign-On,简称 SSO)是一种身份验证和授权机制,它允许用户使用一组凭据(如用户名和密码)来访问多个应用程序而无需重复登录。OAuth 2.0 是一种常用的用于实现单登录的协议。 在 Spring Boot 中实现 OAuth 2.0 单登录,可以使用 Spring Security 提供的相关功能。以下是一个简单的示例: 1. 添加依赖: 在 pom.xml 文件中添加相关依赖,包括 Spring Security 和 OAuth 2.0 相关的库。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> ``` 2. 配置认证服务器: 在 application.properties 或 application.yml 文件中配置认证服务器的相关信息,包括客户端 ID、客户端密钥、授权服务器 URL 等。 ```yaml spring: security: oauth2: client: registration: my-client-id: client-id: your-client-id client-secret: your-client-secret # 其他配置项... provider: my-auth-server: authorization-uri: https://example.com/oauth/authorize token-uri: https://example.com/oauth/token # 其他配置项... ``` 3. 配置安全规则: 创建一个类继承 `WebSecurityConfigurerAdapter`,并重写 `configure(HttpSecurity http)` 方法来配置安全规则。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .oauth2Login() .defaultSuccessUrl("/home") .and() .logout() .logoutSuccessUrl("/login") .and() .csrf().disable(); } } ``` 以上示例中,`/login` 是登录页面的 URL,`/home` 是登录成功后跳转的页面 URL。 4. 创建控制器: 创建一个控制器类,用于处理登录成功后的回调和其他业务逻辑。 ```java @Controller public class HomeController { @GetMapping("/home") public String home() { // 处理登录成功后的逻辑 return "home"; } } ``` 5. 编写前端页面: 根据实际需求,编写登录页面和其他需要登录权限的页面。 以上是一个简单的示例,实际的单登录场景可能涉及更复杂的配置和逻辑。具体的实现方式取决于你使用的身份认证和授权服务器。你可以根据自己的需求进行相应的设置和扩展。 注意:这只是一个基本的示例,实际应用中需要根据具体情况进行配置和开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不务专业的程序员--阿飞

兄弟们能否给口饭吃

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值