SpringBoot使用AutoConfiguration自动配置Bean

当我们需要将我们的bean创建打包成jar给其他项目使用时,使用AutoConfiguration来创建bean是比较好的选择~

假设我们需要自动配置这样的类

java 复制代码
package local.my_sb4.autoconfigure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义服务类
 * 这是自动配置将要创建和管理的bean
 */
public class CustomService {
    private static final Logger logger = LoggerFactory.getLogger(CustomService.class);
    private final CustomServiceProperties properties;
    public CustomService(CustomServiceProperties properties) {
        this.properties = properties;
        logger.info("初始化自定义服务: {}", properties.getName());
    }
    /**
     * 执行业务操作
     * @param input 输入参数
     * @return 处理结果
     */
    public String process(String input) {
        logger.debug("处理输入: {}", input);
        
        if (!properties.isEnabled()) {
            logger.warn("服务已禁用");
            return "Service is disabled";
        }
        
        try {
            // 模拟业务处理
            String result = String.format("[%s] 处理结果: %s (超时: %dms, 重试: %d次)", 
                properties.getName(), input, properties.getTimeout(), properties.getMaxRetries());
            
            logger.info("处理完成: {}", result);
            return result;
            
        } catch (Exception e) {
            logger.error("处理失败", e);
            throw new RuntimeException("处理失败: " + e.getMessage(), e);
        }
    }
    /**
     * 获取服务信息
     * @return 服务信息
     */
    public String getServiceInfo() {
        return String.format("服务名称: %s, 描述: %s, 状态: %s", 
            properties.getName(), properties.getDescription(), properties.isEnabled() ? "启用" : "禁用");
    }
    /**
     * 健康检查
     * @return 健康状态
     */
    public boolean isHealthy() {
        return properties.isEnabled();
    }
}

首先我们需要引入支持自动配置的的依赖

plain 复制代码
dependencies {
        // ...其他依赖
	// 添加自动配置相关依赖
	annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
	implementation 'org.springframework.boot:spring-boot-autoconfigure'
}

我们希望我们的想配置的类有自己的Properties类

java 复制代码
package local.my_sb4.autoconfigure;

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

/**
 * 自定义自动配置属性类
 * 用于配置自定义服务的行为
 */
@ConfigurationProperties(prefix = "custom.service")
public class CustomServiceProperties {
    /**
     * 是否启用自定义服务
     */
    public boolean enabled = true;
    /**
     * 服务名称
     */
    public String name = "default-service";
    /**
     * 服务描述
     */
    public String description = "自定义自动配置服务";
    /**
     * 超时时间(毫秒)
     */
    public long timeout = 5000;
    /**
     * 最大重试次数
     */
    public int maxRetries = 3;
}

现在开始编写我们的自动配置类

  1. 它要被@AutoConfiguration修饰
  2. 如果希望被配置的类存在时才配置,那么需要使用@ConditionalOnClass(目标类.class)来修饰
  3. 如果希望使用自己恶配置类,则需要@EnableConfigurationProperties(配置类.class)来修饰
  4. 如果希望某个配置参数为特定的值或为空时才进行配置,那么需要@ConditionalOnProperty(prefix = "参数名称前缀", name = "参数名称", havingValue = "特定值", matchIfMissing = true)

然后,我们的自动配置类是这样的

java 复制代码
package local.my_sb4.autoconfigure;

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * 自定义服务自动配置类
 * 这是Spring Boot自动配置的核心类
 */
@AutoConfiguration //表示这是一个自动配置类
@ConditionalOnClass(CustomService.class) //当类路径下存在CustomService时才加载
@EnableConfigurationProperties(CustomServiceProperties.class) //启用自定义服务配置属性
@ConditionalOnProperty(prefix = "custom.service", name = "enabled", havingValue = "true", matchIfMissing = true) //当配置项custom.service.enabled=true或空时加载
public class CustomServiceAutoConfiguration {
    /**
     * 创建自定义服务Bean
     * 当容器中不存在CustomService类型的Bean时才会创建
     * 
     * @param properties 配置属性
     * @return 自定义服务实例
     */
    @Bean
    @ConditionalOnMissingBean
    public CustomService customService(CustomServiceProperties properties) {
        return new CustomService(properties);
    }
}

如果需要启用自动配置,还需要编辑*.imports文件以让spring找到我们的自动配置类

resources/META-INF/spring/目录创建org.springframework.boot.autoconfigure.AutoConfiguration.imports文件;

文件的内容是通过换行分隔的自动配置类全限定名称local.my_sb4.autoconfigure.CustomServiceAutoConfiguration

现在开始使用这个自动配置

假设引用我们自动配置的项目这样配置了参数

properties 复制代码
# 自定义服务配置
custom.service.enabled=true
custom.service.name=my-custom-service
custom.service.description=我的自定义自动配置服务
custom.service.timeout=10000
custom.service.max-retries=5

启动应用将会打印

plain 复制代码
2025-12-15T14:55:46.207+08:00  INFO 77305 --- [my_sb4] [           main] l.my_sb4.autoconfigure.CustomService     : 初始化自定义服务: default-service

说明我们的自动配置成功了~

现在编写一个controller来使用我们自动配置的类

java 复制代码
package local.my_sb4.controller;

import local.my_sb4.autoconfigure.CustomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 自定义服务测试控制器
 * 用于测试自定义自动配置是否生效
 */
@RestController
@RequestMapping("/api/custom")
public class CustomServiceController {
    @Autowired
    private CustomService customService;
    /**
     * 测试自定义服务
     * @param input 输入参数
     * @return 处理结果
     */
    @GetMapping("/process")
    public String process(@RequestParam(value = "input", defaultValue = "测试输入") String input) {
        return customService.process(input);
    }
    /**
     * 获取服务信息
     * @return 服务信息
     */
    @GetMapping("/info")
    public String getServiceInfo() {
        return customService.getServiceInfo();
    }
    /**
     * 健康检查
     * @return 健康状态
     */
    @GetMapping("/health")
    public String healthCheck() {
        boolean isHealthy = customService.isHealthy();
        return "{\"status\": \"" + (isHealthy ? "UP" : "DOWN") + "\"}";
    }
}

我们来测试下

启动应用,通过curl来测试

shell 复制代码
fqy@fqyPC my_sb4 % curl "http://127.0.0.1:8080/api/custom/process?input=test"
[default-service] 处理结果: test (超时: 5000ms, 重试: 3次)%                                                                                                                                                                                                                        fqy@fqyPC my_sb4 % curl localhost:8080/api/custom/info
服务名称: default-service, 描述: 自定义自动配置服务, 状态: 启用%                                                                                                                                                                                                                   fqy@fqyPC my_sb4 % curl localhost:8080/api/custom/health
{"status": "UP"}% 

测试结果符合我们的预期~

相关推荐
E***U9453 小时前
从新手到入门:如何判断自己是否真的学会了 Spring Boot
数据库·spring boot·后端
invicinble3 小时前
javase-异常体系
开发语言·spring boot
招风的黑耳3 小时前
智慧养老项目:当SpringBoot遇到硬件,如何优雅地处理异常与状态管理?
java·spring boot·后端
hgz07104 小时前
Spring Boot Starter机制
java·spring boot·后端
daxiang120922054 小时前
Spring boot服务启动报错 java.lang.StackOverflowError 原因分析
java·spring boot·后端
他是龙5514 小时前
第40天:JavaEE安全开发SpringBoot JWT身份鉴权与打包部署(JAR&WAR)
spring boot·安全·java-ee
哈哈老师啊5 小时前
Springboot简单二手车网站qs5ed(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
JIngJaneIL5 小时前
基于Java+ vue图书管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
VX:Fegn08955 小时前
计算机毕业设计|基于springboot + vue考勤管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计