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"}% 

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

相关推荐
hashiqimiya11 小时前
springboot事务触发滚动与不滚蛋
java·spring boot·后端
因我你好久不见11 小时前
Windows部署springboot jar支持开机自启动
windows·spring boot·jar
无关868812 小时前
SpringBootApplication注解大解密
spring boot
追梦者12314 小时前
springboot整合minio
java·spring boot·后端
帅气的你14 小时前
Spring Boot 集成 AOP 实现日志记录与接口权限校验
java·spring boot
计算机毕设VX:Fegn089515 小时前
计算机毕业设计|基于springboot + vue在线音乐播放系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
计算机毕设VX:Fegn089515 小时前
计算机毕业设计|基于springboot + vue博物馆展览与服务一体化系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
帅气的你15 小时前
Spring Boot 1.x 接口性能优化:从 3 秒到 200 毫秒的实战调优之路
java·spring boot
yangminlei16 小时前
Spring Boot/Spring MVC核心注解深度解析
spring boot
goodlook012316 小时前
监控平台搭建-日志-springboot直接推送loki篇(九)
java·spring boot·后端·grafana