1、自定义注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({InitSpringListener.class})
public @interface EnableTest {
}
2、spring boot加上自定义的注解
@Slf4j
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableTest
public class TestApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(TestApplication.class);
ApplicationContext ctx = app.run(args);
}
}
启动所调用的类
@Slf4j
public class InitSpringListener implements ApplicationListener<ApplicationReadyEvent> {
@SneakyThrows
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
Map<String, Object> serviceMap = applicationContext.getBeansWithAnnotation(Service.class);
for (Map.Entry<String, Object> entry : serviceMap.entrySet()) {
Object obj = entry.getValue();
// 从spring容器取出来的,被包了一层代理,此刻需要进行解析
if (AopUtils.isAopProxy(obj)) {
if (AopUtils.isJdkDynamicProxy(obj)) {
Field h = obj.getClass().getSuperclass().getDeclaredField("h");
h.setAccessible(true);
AopProxy aopProxy = (AopProxy) h.get(obj);
Field advised = aopProxy.getClass().getDeclaredField("advised");
advised.setAccessible(true);
obj = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
} else {
// 属性为 CGLIB$CALLBACK_0 即是生成的 dynamicAdvisedInterceptor 对象
Field h = obj.getClass().getDeclaredField("CGLIB$CALLBACK_0");
h.setAccessible(true);
Object dynamicAdvisedInterceptor = h.get(obj);
// dynamicAdvisedInterceptor 中属性为 advised 则是最终被代理的对象
Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
advised.setAccessible(true);
obj = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
}
}
assert obj != null;
Class<?> clazz = obj.getClass();
final Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(clazz);
for (Method method : methods) {
System.out.println(method.getName());
}
}
}
}