第一步定义一个注解。
第二步处理被注解的类,在处理时,可以实现两个类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为值)。
来源:CSDN
作者:chuixue24
链接:https://blog.csdn.net/chuixue24/article/details/104275237