方案1:使用ListableBeanFactory.getBeansWithAnnotation

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class MyBeanProcessor {
    @Autowired
    private ApplicationContext applicationContext;
public void processAnnotatedBeans() { // 获取所有 Bean 的名称 String[] beanNames = applicationContext.getBeanDefinitionNames(); for (String beanName : beanNames) { // 获取 Bean 的实例 Object bean = applicationContext.getBean(beanName); // 检查 Bean 的类是否有指定的注解 if (bean.getClass().isAnnotationPresent(MyCustomAnnotation.class)) { // 处理标注了自定义注解的 Bean System.out.println("Found annotated bean: " + bean.getClass().getName()); } } } }

  

 

方案2:使用ClassPathScanningCandidateComponentProvider

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.util.Set;

public class MyBeanScanner {

    public void scanForAnnotatedBeans(String basePackage) {
        // 创建扫描器,并设置为只考虑注解标注的类
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        // 添加过滤条件,寻找标注了 MyCustomAnnotation 的类
        scanner.addIncludeFilter(new AnnotationTypeFilter(MyCustomAnnotation.class));

        // 扫描指定包下的所有候选组件
        Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(basePackage);
        for (BeanDefinition beanDefinition : candidateComponents) {
            // 打印找到的 Bean 类名
            if (beanDefinition instanceof AnnotatedBeanDefinition) {
                AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition;
                System.out.println("Found annotated bean: " + annotatedBeanDefinition.getBeanClassName());
            }
        }
    }
}


public class Application {
    public static void main(String[] args) {
        MyBeanScanner scanner = new MyBeanScanner();
        scanner.scanForAnnotatedBeans("com.example.package"); // 替换为实际的包名
    }
}

  

posted on 2025-05-26 16:56  卡米i  阅读(2)  评论(0)    收藏  举报