インタビュアー: Spring にカスタム アノテーションをスキャンさせるにはどうすればよいですか?

Spring のアノテーションを使用して@ComponentScan@ImportResourceSpring にカスタム アノテーションをスキャンさせることができます。

まず、猫と犬をマークするためのカスタム アノテーション 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