@Component、@Autowired无效的问题(空指针、得到空对象)

本文记录了一次在 SpringBoot 开发中遇到的 @Component 和 @Autowired 注解失效导致空指针的问题。问题出在测试类中通过 new 函数创建了 GenerallyUtils 对象,而非从 Spring 容器中获取,因此 @Autowired 未生效。解决方案是通过 @Autowired 注解注入 GenerallyUtils 实例,确保使用的是 Spring 管理的对象,从而避免空指针异常。

@Component、@Autowired无效的问题(空指针、得到空对象)

记录一次再开发中遇到的问题,springboot 中的@Component、@Autowired注入无效,

话不多说,直接上代码

用@Component注解将MyWebDriver类注入容器中

@Component("myWebDriver")
public class MyWebDriver {
    public WebDriver getWebDriver(String driver,String driverPath){
        buildWebDriver();
        return webDriver;
    }
}

在GenerallyUtils类中注入myWebDriver,并调用myWebDriver的getWebDriver的方法

@Component
public class GenerallyUtils {
    @Autowired
    MyWebDriver myWebDriver;

    public void getHtmlTagTree(String xpath){
        WebDriver driver = myWebDriver.getWebDriver();
    }
}

测试类,调用generallyUtils中的getHtmlTagTree方法.

@SpringBootTest
class AutomatedApplicationTests {
    @Test
    public void test02() throws InterruptedException {
        new GenerallyUtils().getHtmlTagTree("");
    }

}

到这里就开始报空指针的错误,myWebDriver为null。其实我在这里犯了一个很严重的错误,就是我在测试类中new了一个新的GenerallyUtils对象来调用它的方法。而我们之前就已经把GenerallyUtils交给springboot来管理,这里new出来的对象是一个全新的对象,并非springboot容器中的对象,springboot也不会自动帮我们注入这个对象中的myWebDriver属性,所以此时GenerallyUtils中的myWebDriver为空。

所以此时我们只需要注入springboot容器中的GenerallyUtils就可以了

@SpringBootTest
class AutomatedApplicationTests {
    @Autowired
    GenerallyUtils generallyUtils;
    @Test
    public void test02() throws InterruptedException {
        generallyUtils.getHtmlTagTree("");
    }

}

吸取教训,希望以后不要再犯这种低级错误

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值