You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring5非Spring Boot环境下如何按名称规则注册带指定注解的Bean

Spring 5 无Spring Boot环境下的实现方案

要实现类名以ApplicationService结尾的公共类自动注册为带@Service、@Transactional等效能力的Spring Bean,可按以下步骤操作:

1. 核心思路

  • 通过自定义类路径扫描规则,自动识别符合命名规则的类并注册为Spring Bean,等效于@Service的注册效果
  • 通过Spring事务切面配置,给所有匹配的Bean自动添加事务增强能力,等效于类上标注@Transactional的效果

2. 注解配置实现(推荐)

直接基于Spring原生注解配置,无需引入额外依赖:

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import org.springframework.transaction.interceptor.*;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.FilterType;
import org.springframework.transaction.TransactionDefinition;

@Configuration
@EnableTransactionManagement // 启用Spring事务驱动能力
@ComponentScan(
    // 替换为你自己的业务包路径
    basePackages = "com.your.business.package",
    includeFilters = @ComponentScan.Filter(
        type = FilterType.REGEX,
        pattern = ".*ApplicationService$"
    ),
    // 若你原有项目已经启用默认@Component扫描,可删除下一行,避免影响原有Bean注册
    useDefaultFilters = false
)
public class ApplicationServiceConfig {
    // 配置事务管理器,可根据你使用的持久层框架替换为JpaTransactionManager/HibernateTransactionManager等
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    // 配置全局事务属性,和默认@Transactional注解效果一致
    @Bean
    public TransactionAttributeSource serviceTransactionAttributeSource() {
        NameMatchTransactionAttributeSource attributeSource = new NameMatchTransactionAttributeSource();
        RuleBasedTransactionAttribute defaultTxAttr = new RuleBasedTransactionAttribute();
        // 配置事务传播级别、回滚规则等,和@Transactional参数一一对应
        defaultTxAttr.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        defaultTxAttr.setRollbackFor(RuntimeException.class);
        attributeSource.addTransactionalMethod("*", defaultTxAttr);
        return attributeSource;
    }

    // 配置事务拦截器
    @Bean
    public TransactionInterceptor serviceTransactionInterceptor(PlatformTransactionManager transactionManager,
                                                               TransactionAttributeSource serviceTransactionAttributeSource) {
        return new TransactionInterceptor(transactionManager, serviceTransactionAttributeSource);
    }

    // 配置事务切面,仅对ApplicationService结尾的类生效
    @Bean
    public Advisor applicationServiceTxAdvisor(TransactionInterceptor serviceTransactionInterceptor) {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(public * *..*ApplicationService.*(..))");
        return new DefaultPointcutAdvisor(pointcut, serviceTransactionInterceptor);
    }
}

3. 手动扫描实现(无@ComponentScan场景)

如果你的场景不允许使用@ComponentScan注解,可通过BeanDefinitionRegistryPostProcessor手动实现扫描注册:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.RegexPatternTypeFilter;
import java.util.regex.Pattern;

public class ApplicationServiceScannerConfigurer implements BeanDefinitionRegistryPostProcessor {
    private final String baseScanPackage;

    public ApplicationServiceScannerConfigurer(String baseScanPackage) {
        this.baseScanPackage = baseScanPackage;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry);
        // 添加自定义过滤规则,仅扫描类名以ApplicationService结尾的类
        scanner.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*ApplicationService$")));
        scanner.scan(baseScanPackage);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }
}

在Spring配置类中注册该扫描器即可:

@Bean
public ApplicationServiceScannerConfigurer applicationServiceScannerConfigurer() {
    return new ApplicationServiceScannerConfigurer("com.your.business.package");
}

注意事项

  • 若需要调整事务规则,直接修改RuleBasedTransactionAttribute的属性即可,对应@Transactional注解的全部参数
  • 所有被扫描的ApplicationService类必须是公共非抽象类,否则不会被注册为Bean

内容的提问来源于stack exchange,提问作者abuzittin gillifirca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:15:06