2 步搞定自定义springboot starter

本文介绍如何创建自定义的Spring Boot Starter,包括定义自动装配模块和启动器模块,并演示了具体的实现步骤及测试方法。

2 步搞定自定义springboot starter

 

规范

一般情况下,我们会定义 2 个模块,其中一个负责自动装配,另一个负责依赖管理(启动器)

命名规范为:xxx-spring-boot-starter-autoconfigure、 xxx-spring-boot-starter

具体步骤

第1步 定义自动装配器

1.1 新建模块

根据命名规范为: hello-springboot-starter-autoconfigure

1.2 配置maven
<?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.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example.starter</groupId>
    <artifactId>hello-springboot-starter-autoconfigure</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--引入 spring-boot-starter,所有的 starter 都需要引入这个依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>

</project>
1.3 定义装配逻辑

这里我们定义一个 sayhi 的组件,支持自定义前后缀,目的是让使用者直接注入到容器中使用。

1.3.1 定义一个HelloService服务

public class HelloService {

    private HelloProperties helloProperties;

    public HelloProperties getHelloProperties() {
        return helloProperties;
    }

    public void setHelloProperties(HelloProperties helloProperties) {
        this.helloProperties = helloProperties;
    }

    /**
     * say hi 方法
     * @param name
     * @return
     */
    public String sayHi(String name){
        return helloProperties.getPrefix() +"-"+ name +"-"+ helloProperties.getSuffix();
    }
}

1.3.2 定义一个配置类,支持前后缀配置

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

@ConfigurationProperties(value = "example.hello")
public class HelloProperties {
    private String prefix;
    private String suffix;

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }
}

1.3.3 定义自动配置类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.starter.HelloProperties;

@Configuration// 指定为配置类
@ConditionalOnWebApplication // 指定条件:如果是 web 应用就生效
@EnableConfigurationProperties( HelloProperties.class ) // 启动配置 properties
public class HelloServiceAutoconfiguration {

    @Autowired
    private HelloProperties helloProperties;

    @Bean
    public HelloService helloService(){
        HelloService helloService = new HelloService();
        helloService.setHelloProperties(helloProperties);
        return helloService;
    }
}
1.4 定义spring.factories

resources 目录下,新建 META-INF 目录,在目录新增一个名为 spring.factories 的配置文件,内容如下:

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.starter.HelloServiceAutoconfiguration

其中配置格式为 key,value 的格式,换行使用 \ com.example.starter.HelloServiceAutoconfiguration 是我们自定义的自动配置类。

到此位置,自定义自动装配器就搞定了。接下来,我们写一下启动器

第2步 定义启动器

2.1 新建模块

名为:hello-springboot-starter

当然我这里没有按照规范命名,最好命名为: hello-spring-boot-starter

2.2 配置 maven

这里要引入自动装配模块

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!--自定义starter启动器-->
    <groupId>com.example.starter</groupId>
    <artifactId>hello-springboot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--引入自动装配模块-->
        <dependency>
            <groupId>com.example.starter</groupId>
            <artifactId>hello-springboot-starter-autoconfigure</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

</project>

好了,这个starter启动器不需要任何代码,只需要 pom 配置即可。

接下来,我们测试一下。

第3步 使用方式

3.1 配置maven

创建springboot项目,并引入自定义 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.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example.starter</groupId>
    <artifactId>hello-springboot-starter-test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--引入自定义 starter-->
        <dependency>
            <groupId>com.example.starter</groupId>
            <artifactId>hello-springboot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
3.2 配置properties

当然这一步不是必要的,因为我们的案例支持自定义前后缀,所以要测试一下。

application.properties 配置文件配置我们定义的规则

example.hello.prefix=Welcome
example.hello.suffix=Hands up!!!
3.3 定义测试代码

因为是自动装配,我们可以直接使用 @Autowired private HelloService helloService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    private HelloService helloService;

    @GetMapping("hello/{name}")
    public String hello(@PathVariable("name") String name){
        return helloService.sayHi(name);
    }
}
3.4 启动测试

项目启动后,访问浏览器 http://localhost:8080/hello/Jack

源代码见: https://gitee.com/yunnasheng/springboot-examples/tree/master/springboot-starter

<think>首先,用户的问题是:“我想在Spring Boot应用中集成Google单点登录功能 请问Spring Boot 集成 Google OAuth2 单点登录 实现方法”。这是一个关于在Spring Boot中集成Google单点登录的具体实现方法。 系统级指令: - 所有行内数学表达式必须使用$...$格式,但在这个上下文中,可能没有数学表达式,所以我可以忽略。 - 独立公式必须使用$$...$$格式并单独成段,同样,可能不需要。 - LaTeX语法正确:确保在需要时正确使用。 - 使用中文回答。 - 生成相关问题:在回答结束后,添加“相关问题”部分。 - 回答中引用的段落末尾自然地添加引用标识,例如[^1]。 - 回答结构清晰,帮助用户逐解决问题。 - 保证回答真实可靠。 用户提供的引用: - 引用[1]:关于Spring Security OAuth2实现单点登录和集成第三方登录。 - 引用[2]:在Spring Boot中集成OAuth2实现安全认证。 - 引用[3]:Spring Boot集成OAuth2实现单点登录。 - 引用[4]:Spring Boot基于OAuth2.0实现单点登录全解析。 这些引用是相关的,我应该参考它们来提供准确的实现方法。用户的问题是针对Google单点登录的具体实现。 关键点: - 使用OAuth2协议。 - 集成Google作为第三方登录。 -Spring Boot应用中实现。 实现骤: 1. 设置Google API控制台项目。 2. 添加依赖到Spring Boot项目。 3. 配置OAuth2属性。 4. 实现安全配置。 5. 测试登录功能。 基于引用: - 引用[2]提到“在Spring Boot中集成OAuth2,实现安全认证和授权,并提供一些实际应用案例”。 - 引用[1]说“轻松搞定OAuth2集成”,并提到Google、GitHub。 - 引用[3]和[4]是关于单点登录的。 所以,我应该提供一个逐指南。 回答结构: 1. **引言**:简要介绍Google OAuth2单点登录。 2. **前置条件**:需要Google账户和API密钥。 3. **骤1:在Google API控制台创建项目**。 4. **2:添加Spring Boot依赖**。 5. **骤3:配置application.properties**。 6. **骤4:创建安全配置类**。 7. **骤5:测试应用**。 8. **结论**:总结。 9. **相关问题**:生成相关问题。 确保使用中文。 添加引用标识:在引用的段落末尾添加[^数字]。由于用户提供了引用,我应该基于那些内容自然地添加引用。例如,当提到一般概念时,可以引用[^1]或[^2]。 生成相关问题:在最后添加“相关问题”部分,类似于示例。 具体骤: - **在Google API控制台创建项目**: - 登录Google Cloud Console。 - 创建新项目。 - 启用OAuth2 API。 - 创建OAuth2客户端ID和密钥。 - 设置授权重定向URI(如http://localhost:8080/login/oauth2/code/google)。 - **添加依赖**:在pom.xml中添加Spring Security OAuth2客户端依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> ``` - **配置属性**:在application.properties中设置Google OAuth2属性。 ``` spring.security.oauth2.client.registration.google.client-id=YOUR_CLIENT_ID spring.security.oauth2.client.registration.google.client-secret=YOUR_CLIENT_SECRET spring.security.oauth2.client.registration.google.scope=email,profile ``` - **创建安全配置**:使用@EnableWebSecurity和配置OAuth2登录。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests(authorize -> authorize .anyRequest().authenticated() ) .oauth2Login(withDefaults()); } } ``` - **测试**:运行应用,访问http://localhost:8080/login,应该重定向到Google登录。 添加引用: - 当提到OAuth2简介时,可以引用[^1]或[^2]。 - 当提到单点登录实现时,引用[^3]或[^4]。 例如: - OAuth2是一种强大的授权协议,用于实现安全的单点登录[^1]。 -Spring Boot中集成OAuth2可以简化认证过程[^2]。 相关问题: 生成3-5个相关问题,基于用户查询。 例如: 1. 如何自定义OAuth2登录后的用户信息? 2. Spring Boot集成GitHub单点登录的骤是什么? 3. OAuth2单点登录的安全性如何保障? 4. 如何处理OAuth2回调错误? 5. 如何将OAuth2用户信息存储到数据库? 现在,构建回答。</think>### Spring Boot 集成 Google OAuth2 单点登录实现方法 在 Spring Boot 应用中集成 Google 单点登录功能,主要通过 OAuth2 协议实现。OAuth2 是一种标准授权协议,允许用户使用 Google 账户登录你的应用,而无需暴露其凭证,适用于单点登录(SSO)场景[^1]。以下是一个逐指南,基于 Spring Security OAuth2 客户端实现。整个过程分为 5 个主要骤,确保你已安装 JDK、Maven/Gradle 和 IDE(如 IntelliJ IDEA)。 #### 骤 1: 在 Google API 控制台创建项目并获取凭证 这是前置条件,你需要注册 Google Cloud 项目并配置 OAuth2 客户端。 1. **登录 Google Cloud Console**:访问 [Google Cloud Console](https://console.cloud.google.com/),使用你的 Google 账户登录。 2. **创建新项目**:点击“选择项目” > “新建项目”,输入项目名称(如 "SpringBoot-SSO-Demo"),然后点击“创建”。 3. **启用 OAuth2 API**:在左侧菜单选择“API 和服务” > “库”,搜索“Google+ API”并启用它(Google 登录依赖此 API)。 4. **配置 OAuth2 同意屏幕**: - 在“API 和服务” > “OAuth 同意屏幕”中,选择“外部”用户类型。 - 填写应用名称(如 "My Spring Boot App")、用户支持邮箱等必填项。 - 在“范围”部分,添加 `email` 和 `profile` 权限。 5. **创建 OAuth2 客户端 ID**: - 在“API 和服务” > “凭据”中,点击“创建凭据” > “OAuth 客户端 ID”。 - 应用类型选择“Web 应用”。 - 在“授权重定向 URI”中添加你的应用回调 URL,例如:`http://localhost:8080/login/oauth2/code/google`(本地测试用)。 - 点击“创建”,记录生成的 **客户端 ID** 和 **客户端密钥**。这些将在后续骤中使用。 此骤确保 Google 能识别你的应用并处理登录请求。OAuth2 的核心优势是简化认证流程[^2]。 #### 2: 添加 Spring Boot 依赖 在 Spring Boot 项目中,添加必要的依赖以支持 OAuth2 客户端功能。使用 Maven 或 Gradle 配置。 - **Maven 用户**:在 `pom.xml` 中添加以下依赖: ```xml <dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Security OAuth2 Client --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> <!-- 可选:Thymeleaf 用于简单前端 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> ``` - **Gradle 用户**:在 `build.gradle` 中添加: ```gradle dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' // 可选 } ``` 这些依赖提供了 OAuth2 集成的基础,Spring Security 会自动处理认证流程[^3]。 #### 骤 3: 配置 application.properties 在 `src/main/resources/application.properties` 文件中,设置 Google OAuth2 属性。使用骤 1 中获取的客户端 ID 和密钥。 ```properties # 服务器端口配置 server.port=8080 # Google OAuth2 注册信息 spring.security.oauth2.client.registration.google.client-id=YOUR_CLIENT_ID spring.security.oauth2.client.registration.google.client-secret=YOUR_CLIENT_SECRET spring.security.oauth2.client.registration.google.scope=email,profile spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google # 可选:自定义登录路径(默认 /login) spring.security.oauth2.client.login-path=/login ``` - 替换 `YOUR_CLIENT_ID` 和 `YOUR_CLIENT_SECRET` 为你的 Google 凭证。 - `scope` 指定请求的权限(`email` 和 `profile` 用于获取用户基本信息)。 - `redirect-uri` 必须与 Google Cloud Console 中设置的一致,否则会报错。 此配置使 Spring Boot 自动与 Google 的 OAuth2 服务通信[^2]。 #### 骤 4: 创建安全配置类 实现一个安全配置类来启用 OAuth2 登录。在 `src/main/java/com/example/demo/config` 目录下创建 `SecurityConfig.java` 文件。 ```java package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests(authorize -> authorize .antMatchers("/", "/public/**").permitAll() // 允许公开访问的路径 .anyRequest().authenticated() // 其他路径需要认证 ) .oauth2Login(oauth2 -> oauth2 .loginPage("/login") // 自定义登录页面(可选) .defaultSuccessUrl("/home") // 登录成功后重定向 ) .logout(logout -> logout .logoutSuccessUrl("/") // 登出后重定向 ); } } ``` - **解释**: - `@EnableWebSecurity` 启用 Spring Security。 - `authorizeRequests()` 定义访问规则:这里所有请求都需要认证(`authenticated()`),但 `/public/**` 路径允许匿名访问。 - `oauth2Login()` 配置 OAuth2 登录:默认使用 Google 作为提供者(根据 `application.properties` 自动识别)。 - 可选:添加一个简单控制器来显示用户信息(例如,在 `HomeController.java` 中): ```java @RestController public class HomeController { @GetMapping("/home") public String home(@AuthenticationPrincipal OAuth2User user) { return "欢迎, " + user.getAttribute("name") + "! 你的邮箱: " + user.getAttribute("email"); } } ``` 此配置实现了单点登录的核心逻辑,Spring Security 会自动处理令牌交换和用户信息获取[^4]。 #### 骤 5: 测试应用 运行应用并验证 Google 登录功能。 1. **启动应用**:在 IDE 中运行 `SpringBootApplication` 主类,或使用命令 `mvn spring-boot:run`。 2. **访问登录页面**:打开浏览器,访问 `http://localhost:8080/login`(或你自定义的路径)。Spring Security 会自动重定向到 Google 登录页面。 3. **登录并授权**:输入你的 Google 账户凭据,同意授权请求。 4. **验证成功**:登录后,应用会重定向到 `/home`(或你设置的 URL),并显示用户信息(如名称和邮箱)。 - 如果遇到错误(如 "Invalid redirect_uri"),检查 Google Cloud Console 中的重定向 URI 是否与 `application.properties` 一致。 #### 注意事项和最佳实践 - **安全性**:确保在生产环境中使用 HTTPS,并限制 `redirect-uri` 到你的域名。OAuth2 提供 CSRF 保护,但需定期更新密钥[^4]。 - **自定义**:你可以扩展功能,如存储用户信息到数据库(使用 Spring Data JPA),或集成其他提供者(如 GitHub)。 - **性能**:OAuth2 登录通常快速,但首次请求可能有延迟(由于令牌交换)。 - **问题排查**:常见错误包括凭证错误或范围缺失;查看 Spring Boot 日志(日志级别设为 `DEBUG`)获取详细信息。 通过以上骤,你的 Spring Boot 应用已成功集成 Google 单点登录。OAuth2 简化了认证流程,提升了用户体验和安全性[^1]。如需进一优化(如添加记住我功能),参考 Spring Security 文档。 ### 相关问题 1. 如何自定义 OAuth2 登录后的用户信息存储到数据库? 2. Spring Boot 集成 GitHub 单点登录的实现骤是什么? 3. OAuth2 单点登录的安全性如何保障?有哪些常见风险? 4. 如何处理 OAuth2 回调中的错误(如无效令牌)? 5. 如何实现多提供者单点登录(如同时支持 Google 和 Facebook)? [^1]: OAuth2 是一种强大的授权协议,用于实现安全的单点登录和第三方集成,如 Google 登录。 [^2]: 在 Spring Boot 中集成 OAuth2 可以简化认证流程,适用于现代 Web 应用。 [^3]: Spring Security 的 OAuth2 客户端模块自动处理令牌管理和用户认证。 [^4]: 实现单点登录时,需注意配置细节和安全性,以防止常见漏洞。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值