Interviewer: How to let Spring scan our custom annotations?

Spring's annotations @ComponentScanand @ImportResourceto let Spring scan our custom annotations.

First, define a custom annotation AnimalType for marking cats and dogs:

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

Next, define the cat and dog classes and mark them with the @AnimalType annotation:

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

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

Then, scan the package path through @ComponentScan in Spring's configuration class, so that it can scan our custom annotations:

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

Finally, start the Spring container to get all classes marked with @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());
    }
}

The output is:

Cat: cat
Dog: dog

Guess you like

Origin blog.csdn.net/weixin_39570751/article/details/130866167