獲取Dao上的自定義註解(瞭解Mybatis與Spring整合原理)

Dao類

@Repository
@Tag("user_tag")
public interface UserDao {

void save(User u)
}

需要是:將dao放入到一個本地Map中,key是Tag註解的內容,值是UserDao的Bean對象,在上層調用的時候直接Map.get("user_tage").save(u)即可

實現1:

實現接口BeanPostProcessor

@Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        try {

            //Spring-Mybatis通過MapperScanner會將Dao的接口注入到MapperFactory中,並且將這個MapperFactory已Bean的形式注入到spring中。
            // 即有幾個dao就會有幾個MapperFactory
            //在我們實際調用的時候實質上是通過MapperFactory.getObject()獲取對應Dao接口的代理類MapperProxy
            //我們所寫的啊dao中的方法都是通過MapperProxy中的invoke執行的。
            if (!(bean instanceof MapperFactoryBean)) {
                return bean;
            }
            MapperFactoryBean mapperFactoryBean = (MapperFactoryBean) bean;
            //mapperFactory中代理的接口類型。通過獲取這個接口類型的getAnnotation方法獲取對應註解
            Tag annotation =(Tag)mapperFactoryBean.getObjectType().getAnnotation(Tag.class);
            if (annotation != null) {
               tagMap.put(annotation.getValue(),mapperFactoryBean.getObject());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

實現2:

實現接口 ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware

@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String, Object> beansWithAnnotation = ac.getBeansWithAnnotation(Tag.class);
        for(Map.Entry<String, Object> en:beansWithAnnotation.entrySet()){
            Tag annotationOnBean = ac.findAnnotationOnBean(en.getKey(), Tag.class);
            System.out.println(en.getKey()+"==!!"+annotationOnBean);
            tagMap.put(en.getKey(),en.getValue());
        }
    }
    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        this.ac = ac;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章