最新使用自定义注解封装starter框架,需要用到注解扫描,并且对扫描到加了自定义注解的类进行手动实例化,其中TgWebSocketHandler是我自定义的注解类,代码如下:
package com.websocket.annotation;
import java.lang.annotation.*;
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TgWebSocketHandler {
String endPoint() default "";
}
使用@TgWebSocketHandler注解修饰的类如下:
import com.teligen.websocket.annotation.TgWebSocketHandler;
@TgWebSocketHandler(endPoint = "/normal/demo")
public class HandlerDemo implements WebSocketHandler {
...............
}
下面是获取注解并实例化注解修饰的类,而注解修饰的类都实现了WebSocketHandler 接口:
//扫描获取注解
Reflections f=new Reflections(packname);
Set<Class<?>> handlers=f.getTypesAnnotatedWith(TgWebSocketHandler.class);
//手动通过spring实例化handler
for (Class<?> c : handlers) {
try {
//实例化注解修饰的类
WebSocketHandler webSocketHandler= (WebSocketHandler) registerBeanDefinition(c);
//获取注解对象,在这里获取注解的值
TgWebSocketHandler annotation=c.getAnnotation(TgWebSocketHandler.class);
if(StringUtils.isEmpty(annotation.endPoint())){
log.error(c.getName()+"类配置的TgWebSocketHandler注解缺失endPoint属性,获取出错,不能实例化websocket!!");
break;
}
} catch (Exception e) {
e.printStackTrace();}
}
private Object registerBeanDefinition(Class<?> c) {
BeanDefinitionBuilder beanDefinitionBuilder=BeanDefinitionBuilder.genericBeanDefinition(c.getName());
BeanDefinition beanDefinition=beanDefinitionBuilder.getBeanDefinition();
String name=c.getSimpleName();
//首字母变小写
name=Character.toLowerCase(name.charAt(0))+name.substring(1);
//手动注册实例
BeanUtils.registerBeanDefinition(name,beanDefinition);
return BeanUtils.getBean(name);
}