新增全局配置,解决不启动容器单独使用aop时,调用BeanManager报错的问题

This commit is contained in:
aoshiguchen
2022-07-07 10:49:20 +08:00
parent 689118b3a3
commit 6ab126dee7
8 changed files with 274 additions and 165 deletions
@@ -0,0 +1,145 @@
/**
* Copyright (c) 2022 aoshiguchen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fun.asgc.neutrino.core.aop.interceptor;
import fun.asgc.neutrino.core.aop.Invocation;
import fun.asgc.neutrino.core.util.Assert;
import fun.asgc.neutrino.core.util.CollectionUtil;
import fun.asgc.neutrino.core.util.TypeUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
/**
* 默认的拦截器实现
* @author: aoshiguchen
* @date: 2022/6/30
*/
@Slf4j
public class DefaultInterceptor implements Interceptor {
private final List<Filter> filterList = new ArrayList<>();
private final List<ResultAdvice> resultAdviceList = new ArrayList<>();
private final List<ExceptionHandler> exceptionHandlerList = new ArrayList<>();
private String name;
public DefaultInterceptor() {
this.name = this.getClass().getSimpleName();
}
public DefaultInterceptor(String name) {
this.name = name;
}
@Override
public void intercept(Invocation inv) throws Exception {
try {
log.debug("拦截器:{} class:{} method:{} args:{} before", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs());
if (CollectionUtil.notEmpty(filterList)) {
for (Filter filter : filterList) {
if (filter.filtration(inv.getTargetClass(), inv.getTargetMethod(), inv.getArgs())) {
return;
}
}
}
inv.invoke();
Object result = inv.getReturnValue();
log.debug("拦截器:{} class:{} method:{} args:{} result:{} after", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs(), result);
if (CollectionUtil.notEmpty(resultAdviceList)) {
for (ResultAdvice advice : resultAdviceList) {
result = advice.advice(inv.getTargetClass(), inv.getTargetMethod(), result);
}
}
if (null == result) {
result = TypeUtil.getDefaultValue(inv.getReturnType());
}
inv.setReturnValue(result);
log.debug("拦截器:{} class:{} method:{} args:{} result:{} finished.", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs(), result);
} catch (Exception e) {
log.debug("拦截器:{} class:{} method:{} args:{} exception.", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs());
if (CollectionUtil.notEmpty(exceptionHandlerList)) {
for (ExceptionHandler handler : exceptionHandlerList) {
if (handler.support(e)) {
Object result = handler.handle(e);
if (null != result) {
inv.setReturnValue(result);
}
return;
}
}
}
throw e;
}
}
/**
* 注册过滤器
* @param filter
*/
public synchronized void registerFilter(Filter filter) {
Assert.notNull(filter, "过滤器不能为空!");
this.filterList.add(filter);
}
/**
* 注册过滤器
* @param filterList
*/
public synchronized void registerFilter(List<Filter> filterList) {
Assert.notEmpty(filterList, "过滤器不能为空!");
this.filterList.addAll(filterList);
}
/**
* 注册结果处理器
* @param resultAdvice
*/
public synchronized void registerResultAdvice(ResultAdvice resultAdvice) {
Assert.notNull(resultAdvice, "结果处理器不能为空!");
this.resultAdviceList.add(resultAdvice);
}
/**
* 注册结果处理器
* @param resultAdviceList
*/
public synchronized void registerResultAdvice(List<ResultAdvice> resultAdviceList) {
Assert.notEmpty(resultAdviceList, "结果处理器不能为空!");
this.resultAdviceList.addAll(resultAdviceList);
}
/**
* 注册异常处理器
* @param exceptionHandler
*/
public synchronized void registerExceptionHandler(ExceptionHandler exceptionHandler) {
Assert.notNull(exceptionHandler, "异常处理器不能为空!");
this.exceptionHandlerList.add(exceptionHandler);
}
public synchronized void registerExceptionHandler(List<ExceptionHandler> exceptionHandlerList) {
Assert.notEmpty(exceptionHandlerList, "异常处理器不能为空!");
this.exceptionHandlerList.addAll(exceptionHandlerList);
}
}
@@ -22,12 +22,8 @@
package fun.asgc.neutrino.core.aop.interceptor;
import fun.asgc.neutrino.core.aop.Invocation;
import fun.asgc.neutrino.core.util.Assert;
import fun.asgc.neutrino.core.util.CollectionUtil;
import fun.asgc.neutrino.core.util.TypeUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
/**
@@ -40,7 +36,7 @@ public class InnerGlobalInterceptor implements Interceptor {
/**
* 拦截器包装器
*/
private static final InterceptorWrapper interceptorWrapper = new InterceptorWrapper(InnerGlobalInterceptor.class.getSimpleName());
private static final DefaultInterceptor interceptorWrapper = new DefaultInterceptor(InnerGlobalInterceptor.class.getSimpleName());
public InnerGlobalInterceptor() {
@@ -22,6 +22,7 @@
package fun.asgc.neutrino.core.aop.interceptor;
import fun.asgc.neutrino.core.aop.Intercept;
import fun.asgc.neutrino.core.base.GlobalConfig;
import fun.asgc.neutrino.core.cache.Cache;
import fun.asgc.neutrino.core.cache.MemoryCache;
import fun.asgc.neutrino.core.util.*;
@@ -39,6 +40,7 @@ import java.util.stream.Stream;
public class InterceptorFactory {
private static final Cache<Class<? extends Interceptor>, Interceptor> interceptorCache = new MemoryCache<>();
private static final List<Interceptor> globalInterceptorList = Collections.synchronizedList(new ArrayList<>());
private static final Map<Class<?>, List<Interceptor>> classInterceptorListMap = new HashMap<>();
private static final Map<Method, List<Interceptor>> methodInterceptorListMap = new HashMap<>();
private static final Cache<Class<? extends Filter>, Filter> filterCache = new MemoryCache<>();
private static final Cache<Class<? extends ResultAdvice>, ResultAdvice> resultAdviceCache = new MemoryCache<>();
@@ -55,20 +57,21 @@ public class InterceptorFactory {
* @param <T>
* @return
*/
private static <T> T getOrNewCacheBean(Class<T> clazz, Cache cache) throws Exception {
return (T)LockUtil.doubleCheckProcess(() -> !cache.containsKey(clazz),
private static <T> T getOrNewCacheBean(Class<T> clazz, Cache cache) {
return (T)LockUtil.doubleCheckProcessForNoException(() -> !cache.containsKey(clazz),
clazz,
() -> {
try {
// TODO
// cache.set(clazz, clazz.newInstance());
if (BeanManager.getBean(clazz) != null) {
cache.set(clazz, BeanManager.getBean(clazz));
} else {
cache.set(clazz, clazz.newInstance());
Object obj = null;
if (GlobalConfig.isIsContainerStartup()) {
obj = BeanManager.getBean(clazz);
}
if (null == obj) {
obj = clazz.newInstance();
}
cache.set(clazz, obj);
} catch (InstantiationException|IllegalAccessException e) {
throw new RuntimeException(e);
throw e;
}
},
() -> cache.get(clazz)
@@ -82,12 +85,7 @@ public class InterceptorFactory {
* @return
*/
public static <T extends Interceptor> T get(Class<? extends Interceptor> clazz) {
try {
return (T)getOrNewCacheBean(clazz, interceptorCache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
return (T)getOrNewCacheBean(clazz, interceptorCache);
}
/**
@@ -97,12 +95,7 @@ public class InterceptorFactory {
* @return
*/
private static <T extends Filter> T getFilter(Class<? extends Filter> clazz) {
try {
return (T)getOrNewCacheBean(clazz, filterCache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
return (T)getOrNewCacheBean(clazz, filterCache);
}
/**
@@ -125,12 +118,7 @@ public class InterceptorFactory {
* @return
*/
private static <T extends ResultAdvice> T getResultAdvice(Class<? extends ResultAdvice> clazz) {
try {
return (T)getOrNewCacheBean(clazz, resultAdviceCache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
return (T)getOrNewCacheBean(clazz, resultAdviceCache);
}
/**
@@ -153,12 +141,7 @@ public class InterceptorFactory {
* @return
*/
private static <T extends ExceptionHandler> T getExceptionHandler(Class<? extends ExceptionHandler> clazz) {
try {
return (T)getOrNewCacheBean(clazz, exceptionHandlerCache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
return (T)getOrNewCacheBean(clazz, exceptionHandlerCache);
}
/**
@@ -182,30 +165,25 @@ public class InterceptorFactory {
public static List<Interceptor> getListByTargetMethod(Method targetMethod) {
Assert.notNull(targetMethod, "目标方法不能为空!");
try {
return LockUtil.doubleCheckProcess(() -> !methodInterceptorListMap.containsKey(targetMethod),
targetMethod,
() -> {
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(globalInterceptorList);
addInterceptorByAnnotation(interceptors, targetMethod.getDeclaringClass().getAnnotation(Intercept.class));
addInterceptorByAnnotation(interceptors, targetMethod.getAnnotation(Intercept.class));
// 如果被代理方法所属类是一个接口,那么该接口所有继承接口链路上的注解都对该方法生效
if (ClassUtil.isInterface(targetMethod.getDeclaringClass())) {
List<Class<?>> interfaceList = ReflectUtil.getInterfaceAll(targetMethod.getDeclaringClass());
if (CollectionUtil.notEmpty(interfaceList)) {
for (Class<?> clazz : interfaceList) {
addInterceptorByAnnotation(interceptors, clazz.getAnnotation(Intercept.class));
}
return LockUtil.doubleCheckProcessForNoException(() -> !methodInterceptorListMap.containsKey(targetMethod),
targetMethod,
() -> {
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(globalInterceptorList);
addInterceptorByAnnotation(interceptors, targetMethod.getDeclaringClass().getAnnotation(Intercept.class));
addInterceptorByAnnotation(interceptors, targetMethod.getAnnotation(Intercept.class));
// 如果被代理方法所属类是一个接口,那么该接口所有继承接口链路上的注解都对该方法生效
if (ClassUtil.isInterface(targetMethod.getDeclaringClass())) {
List<Class<?>> interfaceList = ReflectUtil.getInterfaceAll(targetMethod.getDeclaringClass());
if (CollectionUtil.notEmpty(interfaceList)) {
for (Class<?> clazz : interfaceList) {
addInterceptorByAnnotation(interceptors, clazz.getAnnotation(Intercept.class));
}
}
methodInterceptorListMap.put(targetMethod, interceptors);
},
() -> methodInterceptorListMap.get(targetMethod));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
methodInterceptorListMap.put(targetMethod, interceptors);
},
() -> methodInterceptorListMap.get(targetMethod));
}
/**
@@ -218,7 +196,7 @@ public class InterceptorFactory {
return;
}
if (ArrayUtil.notEmpty(intercept.filter()) || ArrayUtil.notEmpty(intercept.resultAdvice()) || ArrayUtil.notEmpty(intercept.exceptionHandler())) {
InterceptorWrapper wrapper = new InterceptorWrapper();
DefaultInterceptor wrapper = new DefaultInterceptor();
List<Filter> filterList = getFilterList(intercept.filter());
List<ResultAdvice> resultAdviceList = getResultAdviceList(intercept.resultAdvice());
List<ExceptionHandler> exceptionHandlerList = getExceptionHandlerList(intercept.exceptionHandler());
@@ -23,123 +23,53 @@ package fun.asgc.neutrino.core.aop.interceptor;
import fun.asgc.neutrino.core.aop.Invocation;
import fun.asgc.neutrino.core.util.Assert;
import fun.asgc.neutrino.core.util.CollectionUtil;
import fun.asgc.neutrino.core.util.TypeUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import fun.asgc.neutrino.core.util.LockUtil;
/**
* 拦截器包装器
* 拦截器包装器
* 用于支持拦截器以type或者实例形式注册
*
* 以type类型注册时,拦截器的实例化时机延迟到首次调用
* @author: aoshiguchen
* @date: 2022/6/30
* @date: 2022/7/6
*/
@Slf4j
public class InterceptorWrapper implements Interceptor {
private final List<Filter> filterList = new ArrayList<>();
private final List<ResultAdvice> resultAdviceList = new ArrayList<>();
private final List<ExceptionHandler> exceptionHandlerList = new ArrayList<>();
private String name;
/**
* 拦截器实例
*/
private volatile Interceptor instance;
/**
* 拦截器类型
*/
private Class<? extends Interceptor> type;
public InterceptorWrapper() {
this.name = this.getClass().getSimpleName();
}
private InterceptorWrapper() {
public InterceptorWrapper(String name) {
this.name = name;
}
@Override
public void intercept(Invocation inv) throws Exception {
try {
log.debug("拦截器:{} class:{} method:{} args:{} before", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs());
if (CollectionUtil.notEmpty(filterList)) {
for (Filter filter : filterList) {
if (filter.filtration(inv.getTargetClass(), inv.getTargetMethod(), inv.getArgs())) {
return;
}
}
}
inv.invoke();
Object result = inv.getReturnValue();
log.debug("拦截器:{} class:{} method:{} args:{} result:{} after", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs(), result);
if (CollectionUtil.notEmpty(resultAdviceList)) {
for (ResultAdvice advice : resultAdviceList) {
result = advice.advice(inv.getTargetClass(), inv.getTargetMethod(), result);
}
}
if (null == result) {
result = TypeUtil.getDefaultValue(inv.getReturnType());
}
inv.setReturnValue(result);
log.debug("拦截器:{} class:{} method:{} args:{} result:{} finished.", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs(), result);
} catch (Exception e) {
log.debug("拦截器:{} class:{} method:{} args:{} exception.", this.name, inv.getTargetClass().getName(), inv.getTargetMethod().getName(), inv.getArgs());
if (CollectionUtil.notEmpty(exceptionHandlerList)) {
for (ExceptionHandler handler : exceptionHandlerList) {
if (handler.support(e)) {
Object result = handler.handle(e);
if (null != result) {
inv.setReturnValue(result);
}
return;
}
}
}
throw e;
}
// 若未实例化,则在此先实例化
LockUtil.doubleCheckProcess(
() -> null == instance,
this,
() -> InterceptorFactory.get(type)
);
instance.intercept(inv);
}
/**
* 注册过滤器
* @param filter
*/
public synchronized void registerFilter(Filter filter) {
Assert.notNull(filter, "过滤器不能为空!");
this.filterList.add(filter);
public static InterceptorWrapper create(Class<? extends Interceptor> type) {
Assert.notNull(type, "拦截器类型不能为空!");
InterceptorWrapper wrapper = new InterceptorWrapper();
wrapper.type = type;
return wrapper;
}
/**
* 注册过滤器
* @param filterList
*/
public synchronized void registerFilter(List<Filter> filterList) {
Assert.notEmpty(filterList, "过滤器不能为空!");
this.filterList.addAll(filterList);
}
/**
* 注册结果处理器
* @param resultAdvice
*/
public synchronized void registerResultAdvice(ResultAdvice resultAdvice) {
Assert.notNull(resultAdvice, "结果处理器不能为空!");
this.resultAdviceList.add(resultAdvice);
}
/**
* 注册结果处理器
* @param resultAdviceList
*/
public synchronized void registerResultAdvice(List<ResultAdvice> resultAdviceList) {
Assert.notEmpty(resultAdviceList, "结果处理器不能为空!");
this.resultAdviceList.addAll(resultAdviceList);
}
/**
* 注册异常处理器
* @param exceptionHandler
*/
public synchronized void registerExceptionHandler(ExceptionHandler exceptionHandler) {
Assert.notNull(exceptionHandler, "异常处理器不能为空!");
this.exceptionHandlerList.add(exceptionHandler);
}
public synchronized void registerExceptionHandler(List<ExceptionHandler> exceptionHandlerList) {
Assert.notEmpty(exceptionHandlerList, "异常处理器不能为空!");
this.exceptionHandlerList.addAll(exceptionHandlerList);
public static InterceptorWrapper create(Interceptor instance) {
Assert.notNull(instance, "拦截器实例不能为空!");
InterceptorWrapper wrapper = new InterceptorWrapper();
wrapper.instance = instance;
wrapper.type = instance.getClass();
return wrapper;
}
}
@@ -21,6 +21,7 @@
*/
package fun.asgc.neutrino.core.aop.proxy;
import fun.asgc.neutrino.core.base.GlobalConfig;
import fun.asgc.neutrino.core.util.*;
import lombok.extern.slf4j.Slf4j;
@@ -68,7 +69,9 @@ public class AsgcProxyFactory implements ProxyFactory {
proxyClass.setName(generateClassName(clazz));
String sourceCode = AsgcProxyGenerator.getInstance().generator(proxyClass.getName(), clazz); // generateProxyClassSourceCode(clazz, proxyClass.getName());
proxyClass.setSourceCode(sourceCode);
log.debug("类:{} 的代理类源码:\n{}", clazz.getName(), sourceCode);
if (GlobalConfig.isIsPrintGeneratorCode()) {
log.debug("类:{} 的代理类源码:\n{}", clazz.getName(), sourceCode);
}
compiler.compile(proxyClass);
Class<T> retClass = (Class<T>)classLoader.loadProxyClass(proxyClass);
@@ -0,0 +1,54 @@
/**
* Copyright (c) 2022 aoshiguchen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fun.asgc.neutrino.core.base;
/**
* 全局配置
* @author: aoshiguchen
* @date: 2022/7/7
*/
public class GlobalConfig {
/**
* 是否打印自动生成的代码
*/
private static volatile boolean isPrintGeneratorCode = false;
/**
* 是否是容器启动
*/
private static volatile boolean isContainerStartup = false;
public static boolean isIsPrintGeneratorCode() {
return isPrintGeneratorCode;
}
public static void setIsPrintGeneratorCode(boolean isPrintGeneratorCode) {
GlobalConfig.isPrintGeneratorCode = isPrintGeneratorCode;
}
public static boolean isIsContainerStartup() {
return isContainerStartup;
}
public static void setIsContainerStartup(boolean isContainerStartup) {
GlobalConfig.isContainerStartup = isContainerStartup;
}
}
@@ -27,6 +27,7 @@ import fun.asgc.neutrino.core.aop.interceptor.ExceptionHandler;
import fun.asgc.neutrino.core.aop.interceptor.Filter;
import fun.asgc.neutrino.core.aop.interceptor.Interceptor;
import fun.asgc.neutrino.core.aop.interceptor.ResultAdvice;
import fun.asgc.neutrino.core.base.GlobalConfig;
import fun.asgc.neutrino.core.bean.BeanFactoryAware;
import fun.asgc.neutrino.core.bean.SimpleBeanFactory;
import fun.asgc.neutrino.core.runner.ApplicationRunner;
@@ -79,6 +80,7 @@ public class ApplicationContext implements LifeCycle {
public synchronized void init() {
this.lifeCycleManager.init(() -> {
try {
GlobalConfig.setIsContainerStartup(true);
this.rootBeanFactory = new SimpleBeanFactory("rootBeanFactory");
this.applicationBeanFactory = new SimpleBeanFactory(rootBeanFactory, "applicationBeanFactory");
this.rootBeanFactory.registerBean(environment, "rootEnvironment");
@@ -61,6 +61,7 @@ public class LockUtil {
doubleCheckProcess(isLock, lock, lockProcess);
} catch (Exception e) {
// ignore
e.printStackTrace();
}
}