异常:
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.reflect.InvocationHandler' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Description:
Parameter 0 of constructor in com.sun.proxy.$Proxy77 required a bean of type 'java.lang.reflect.InvocationHandler' that could not be found.
Action:
Consider defining a bean of type 'java.lang.reflect.InvocationHandler' in your configuration.
错误代码:
@Component
public class XHGAProxyScan2 implements ApplicationContextAware,InitializingBean {ApplicationContext applicationContext;@Overridepublic void afterPropertiesSet() throws Exception { }@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;String name = "testApiService";//被代理对象Object proxyB = (TestApi) () -> {System.out.println("------new :↓------");return "new Object: hello";};Class<?> interfaceClass = TestApi.class;XHGAProxy xhgaProxy = new XHGAProxy<>(proxyB);//代理对象Object proxyA = Proxy.newProxyInstance(interfaceClass.getClassLoader(),new Class[]{interfaceClass}, xhgaProxy);// 进行注册步骤:ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;DefaultListableBeanFactory beanFactory =(DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();BeanDefinitionBuilder beanDefinitionBuilder =BeanDefinitionBuilder.genericBeanDefinition(proxyA.getClass());//-------↓添加以下代码/*beanDefinitionBuilder.addConstructorArgValue(Proxy.getInvocationHandler(proxyA));AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();beanDefinition.setBeanClass(proxyA.getClass());*///-------↑beanFactory.registerBeanDefinition(name, beanDefinitionBuilder.getRawBeanDefinition());}
解决方法:
将上面注释的代码取消注释:
//-------↓添加以下代码
beanDefinitionBuilder.addConstructorArgValue(Proxy.getInvocationHandler(proxyA));
AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
beanDefinition.setBeanClass(proxyA.getClass());
//-------↑
参考以下博客完美解决问题:
小眼儿: https://www.cnblogs.com/hujunzheng/p/8527338.html