Spring环境下泛型父类初始化异常:targetWebDriverClass为空问题
问题分析与解决方案
核心原因
Spring默认使用JDK动态代理生成Bean代理,而WebDriverDecorator本身实现了WebDriver接口,导致Spring生成的代理类仅实现WebDriver接口而非继承ProxyDecorator类。父类WebDriverDecorator中初始化的targetWebDriverClass是类实例属性,代理对象无法继承该属性,调用decorate方法时自然会触发空指针异常。非Spring环境下直接实例化类,不存在代理层,所以属性初始化正常。
解决方案
方案1:强制使用CGLIB代理
让Spring通过CGLIB生成基于类继承的代理,这样代理类会完整继承ProxyDecorator的所有属性与方法,确保targetWebDriverClass被正确初始化。
- 方式一:添加注解启用CGLIB代理
在Spring配置类上添加:
@EnableAspectJAutoProxy(proxyTargetClass = true)
- 方式二:通过配置文件开启
在application.properties中添加:
spring.aop.proxy-target-class=true
方案2:手动修复父类属性
如果无法切换代理类型,可在ProxyDecorator中手动重置父类的targetWebDriverClass属性,避免空指针:
@Component public class ProxyDecorator extends WebDriverDecorator<WebDriver> { private static final Class<WebDriver> TARGET_CLASS = WebDriver.class; public ProxyDecorator() { super(TARGET_CLASS); } @Override public WebDriver decorate(WebDriver driver) { // 强制重置父类的targetWebDriverClass属性 try { Field field = WebDriverDecorator.class.getDeclaredField("targetWebDriverClass"); field.setAccessible(true); field.set(this, TARGET_CLASS); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException("Failed to initialize targetWebDriverClass", e); } return super.decorate(driver); } }
方案3:避免代理该Bean
如果ProxyDecorator不需要AOP增强,可排除它的代理生成:
@Component @Scope(proxyMode = ScopedProxyMode.NO) public class ProxyDecorator extends WebDriverDecorator<WebDriver> { public ProxyDecorator() { super(WebDriver.class); } }
内容的提问来源于stack exchange,提问作者Wojciech Kopeć
相关产品推荐
相关产品推荐

