可以使用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<String, Object> 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)