面试官:怎样让Spring扫描我们自定义的注解?

可以使用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

猜你喜欢

转载自blog.csdn.net/weixin_39570751/article/details/130866167