spring将动态代理对象注册为Bean遇到的问题:Unsatisfied dependency expressed through constructor parameter 0; nested e
异常:Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.refl...
异常:
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;
@Override
public void afterPropertiesSet() throws Exception { }
@Override
public 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());
//-------↑
参考以下博客完美解决问题:
更多推荐


所有评论(0)