SpringBootでカスタムアノテーションクラスを取得する方法

Spring Bootでは、カスタムアノテーションクラスをリフレクションによって取得できます。

まず、@ComponentScanアノテーションを使ってアノテーションが配置されたパッケージをスキャンする必要があります。 例えば、カスタムアノテーションクラスがcom.example.annotationsパッケージにある場合、起動クラスに@ComponentScan(“com.example.annotations”)を追加できます。

また、カスタムアノテーションクラスの取得が必要な場所に、リフレクションからアノテーションクラスを取得する方法があります。例えば、カスタムアノテーションクラスが@MyAnnotationの場合、以下のコードを使用してアノテーションクラスを取得できます。

import com.example.annotations.MyAnnotation;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;

@Component
public class MyComponent {

    private final ApplicationContext applicationContext;

    public MyComponent(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void getAnnotationClass() {
        // 获取所有带有MyAnnotation注解的类
        String[] beanNames = applicationContext.getBeanNamesForAnnotation(MyAnnotation.class);

        for (String beanName : beanNames) {
            Class<?> beanClass = applicationContext.getType(beanName);

            // 获取类上的MyAnnotation注解
            MyAnnotation myAnnotation = beanClass.getAnnotation(MyAnnotation.class);

            // 处理注解
            if (myAnnotation != null) {
                // TODO: 处理注解逻辑
            }
        }
    }
}

上記コードでは、まずgetBeanNamesForAnnotationメソッドを使用して、MyAnnotationアノテーションが付与されたすべてのクラスのBean名を取得します. その後、getTypeメソッドでクラスの型を取得します. 最後に、getAnnotationメソッドを使用して、アノテーションインスタンスを取得します。

Spring BootがMyComponentクラスを自動スキャンしてインスタンスを作成できるように、上記コードのMyComponentクラスに@Componentアノテーションを追加することに注意してください。

自身の実情に合わせ調整する必要があります。

bannerAds