spring框架下@Autowried的类为null

spring框架下@Autowried的类为null

2023.3.30

已经数不清第几次出现这种问题了,记录一下,不能再错嘞。

仅在测试类为空

解决前:

@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringContextTest {
    @Autowired
    private UserDao userDao;
    @Test
    public void createUserTest(){
//		  配置文件创建对象
//        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//        User userModel = (User) applicationContext.getBean("userDao");
        userDao.say();
    }
}

解决后:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringContextTest {
    @Autowired
    private UserDao userDao;
    @Test
    public void createUserTest(){
//        配置文件创建对象
//        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//        User userModel = (User) applicationContext.getBean("userModel");
        userDao.say();
    }
}

原因:需要将测试的环境交给spring去管理,也就是添加注解

@RunWith(SpringJUnit4ClassRunner.class)

这个注解参数不唯一,百度也有很多这种解决方案

  • 稍提一嘴,Spring boot中也有这种情况,解决方案同理,将测试环境交给spring管理
@SpringBootTest         //添加测试环境
class LeagueConstructionApplicationTests {
    @Autowired
    ManagerMapper managerMapper;
    @Autowired
    ManagerService managerService;
    @Autowired
    Manager manager;
    @Test
    void contextLoads() {
        manager.setManager_state(0);
        System.out.println(managerMapper.findSomeManager(manager));
    }
}

测试为null且实际使用也为null

这个问题基本不会出现在初学者身上,大多都是出现在学完spring boot开发了很久回头使用spring原生框架的时候会发生的事(个人认为如此,本人就是例子),spring boot注重于“约定由于配置”,这是为了使程序员在开发过程中不必过多将时间花费在配置文件上,从而专心开发业务。spring原生框架是提到了:如果需要使用注解模式,需要在对应的配置文件中开启注解扫描,即:

<context:component-scan base-package="model,dao"/>

需要修改其命名空间

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
<beans>

同时还需要注意一点,如果在运行过程中报错:String类无法被注入或者Integer类无法被注入之类的,那么恭喜已经解决了这个问题,就是下次用lombok的时候需要小小的写上空参构造和全参构造注解。
报错如下:

No qualifying bean of type 'java.lang.String' available
No qualifying bean of type 'java.lang.Integer' available
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值