随笔 - 434,  文章 - 0,  评论 - 463,  阅读 - 46万

可以使用Spring的注解 @ComponentScan@ImportResource 来让Spring扫描我们自定义的注解。

首先,定义一个自定义注解 AnimalType,用于标记猫和狗:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnimalType {
    String value();
}

接着,定义猫和狗类,分别标记上 @AnimalType 注解:

@AnimalType("cat")
public class Cat {
    // ...
}

@AnimalType("dog")
public class Dog {
    // ...
}

然后,在Spring的配置类中通过 @ComponentScan 扫描包路径,使其能够扫描到我们自定义的注解:

@Configuration
@ComponentScan(basePackages = "com.example.animals")
public class AppConfig {
    // ...
}

最后,启动Spring容器即可获取所有被 @AnimalType 标记的类:

public static void main(String[] args) {
    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    Map<StringObject> animalMap = context.getBeansWithAnnotation(AnimalType.class);
    for (Object animal : animalMap.values()) {
        System.out.println(animal.getClass().getSimpleName() + ": " + ((AnimalType)animal.getClass().getAnnotation(AnimalType.class)).value());
    }
}

输出结果为:

Cat: cat
Dog: dog

posted on   剽悍一小兔  阅读(453)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示