spring筆記-AnnotationAttributes

1.注解的解析轉換

通常對注解的解析之后,需要對注解的信息進行對象存儲轉換,
比如EnableMongoRepositories注解,有13個屬性,如下定義

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(MongoRepositoriesRegistrar.class)
public @interface EnableMongoRepositories {

    /**
     * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.:
     * {@code @EnableJpaRepositories("org.my.pkg")} instead of {@code @EnableJpaRepositories(basePackages="org.my.pkg")}.
     */
    String[] value() default {};

    /**
     * Base packages to scan for annotated components. {@link #value()} is an alias for (and mutually exclusive with) this
     * attribute. Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names.
     */
    String[] basePackages() default {};

    /**
     * Type-safe alternative to {@link #basePackages()} for specifying the packages to scan for annotated components. The
     * package of each class specified will be scanned. Consider creating a special no-op marker class or interface in
     * each package that serves no purpose other than being referenced by this attribute.
     */
    Class<?>[] basePackageClasses() default {};

    /**
     * Specifies which types are eligible for component scanning. Further narrows the set of candidate components from
     * everything in {@link #basePackages()} to everything in the base packages that matches the given filter or filters.
     */
    Filter[] includeFilters() default {};

    /**
     * Specifies which types are not eligible for component scanning.
     */
    Filter[] excludeFilters() default {};

    /**
     * Returns the postfix to be used when looking up custom repository implementations. Defaults to {@literal Impl}. So
     * for a repository named {@code PersonRepository} the corresponding implementation class will be looked up scanning
     * for {@code PersonRepositoryImpl}.
     * 
     * @return
     */
    String repositoryImplementationPostfix() default "Impl";

    /**
     * Configures the location of where to find the Spring Data named queries properties file. Will default to
     * {@code META-INFO/mongo-named-queries.properties}.
     * 
     * @return
     */
    String namedQueriesLocation() default "";

    /**
     * Returns the key of the {@link QueryLookupStrategy} to be used for lookup queries for query methods. Defaults to
     * {@link Key#CREATE_IF_NOT_FOUND}.
     * 
     * @return
     */
    Key queryLookupStrategy() default Key.CREATE_IF_NOT_FOUND;

    /**
     * Returns the {@link FactoryBean} class to be used for each repository instance. Defaults to
     * {@link MongoRepositoryFactoryBean}.
     * 
     * @return
     */
    Class<?> repositoryFactoryBeanClass() default MongoRepositoryFactoryBean.class;

    /**
     * Configures the name of the {@link MongoTemplate} bean to be used with the repositories detected.
     * 
     * @return
     */
    String mongoTemplateRef() default "mongoTemplate";

    /**
     * Whether to automatically create indexes for query methods defined in the repository interface.
     * 
     * @return
     */
    boolean createIndexesForQueryMethods() default false;

    /**
     * Configures whether nested repository-interfaces (e.g. defined as inner classes) should be discovered by the
     * repositories infrastructure.
     */
    boolean considerNestedRepositories() default false;
}

2.解析方法

2.1 ImportBeanDefinitionRegistrar接口的registerBeanDefinitions方法中有一個AnnotationMetadata類型的參數,可以調用getAnnotationAttributes方法來獲取信息

public interface AnnotatedTypeMetadata {
        //...
    Map<String, Object> getAnnotationAttributes(String annotationName);

2.2 AnnotationAttributes

AnnotationAttributes可以更好的對Map進行封裝處理,直接在構造函數中傳入Map實例即可

2.3 AnnotatedElementUtils

可以使用AnnotatedElementUtils的getMergedAnnotationAttributes方法直接返回AnnotationAttributes實例對象

3.基于AnnotationAttributes更好的封裝

比如上面說的EnableMongoRepositories,在實際中轉換成對象則是AnnotationRepositoryConfigurationSource,如下代碼

public class AnnotationRepositoryConfigurationSource extends RepositoryConfigurationSourceSupport {

    private static final String QUERY_LOOKUP_STRATEGY = "queryLookupStrategy";

    private final AnnotationAttributes attributes;

    public AnnotationRepositoryConfigurationSource(AnnotationMetadata metadata, Class<? extends Annotation> annotation,
            ResourceLoader resourceLoader, Environment environment) {
        this.attributes = new AnnotationAttributes(metadata.getAnnotationAttributes(annotation.getName()));
    }
    public Object getQueryLookupStrategyKey() {
        return attributes.get(QUERY_LOOKUP_STRATEGY);
    }
}

封裝后,在實際使用時會有更好的體驗

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,779評論 18 399
  • 為什么起這么一個題目?不知道,反正首先要聽著文藝。 近幾次出差,坐車行走于云南的山嶺間,在欣賞山河壯闊的同時,感覺...
    王立熠閱讀 231評論 1 3
  • 史蒂芬.柯維曾經說過這樣一段話: “你的影響力在于你的榜樣作用和引導能力,前者源于你的品德,是你的真我,別人的評論...
    銥漩娜閱讀 1,053評論 0 1
  • 晨讀今天分享的書叫《刻意練習》,文中提到舒適區,好多牛人作分享時也會諄諄告誡我們,想要持續進步成長,必須跳出你的舒...
    秋秋絮語閱讀 541評論 1 2