spring自定义注解及其处理

可紊 提交于 2020-02-12 12:28:25

第一步定义一个注解。

第二步处理被注解的类,在处理时,可以实现两个类ApplicationListener, ApplicationContextAware:

@Configuration
public class CreateIndex implements ApplicationListener, ApplicationContextAware {
    @Autowired
    ElasticsearchIndex elasticsearchIndex;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ApplicationContext applicationContext;

    /**
     * 扫描ESMetaData注解的类,并自动创建索引mapping
     * @param event
     */
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        Map<String, Object> beansWithAnnotationMap = this.applicationContext.getBeansWithAnnotation(ESMetaData.class);
        beansWithAnnotationMap.forEach((beanName,bean) ->
                {
                    try {
                        if(!elasticsearchIndex.exists(bean.getClass())){
                            elasticsearchIndex.createIndex(bean.getClass());
                            logger.info("启动创建索引成功");
                        }
                    } catch (Exception e) {
                        logger.error("创建索引不成功",e);
                    }
                }
        );
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

/**
     * Find all beans whose {@code Class} has the supplied {@link Annotation} type,
     * returning a Map of bean names with corresponding bean instances.
     * <p>Note that this method considers objects created by FactoryBeans, which means
     * that FactoryBeans will get initialized in order to determine their object type.
     * @param annotationType the type of annotation to look for
     * @return a Map with the matching beans, containing the bean names as
     * keys and the corresponding bean instances as values
     * @throws BeansException if a bean could not be created
     * @since 3.0
     */

Map<String, Object> org.springframework.beans.factory.ListableBeanFactory.getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException可以获取到被注解的类,结果为一个map:returning a Map of bean names with corresponding bean instances.(以sping bean名字为key,spring bean为值)。

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!