@Autowired只能在Bean中使用吗?

我想在测试类中使用JpaRepository,于是这样写:

// CustomerRepository
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}
// 测试类
public class CustomerTest {
    // 编辑器有一个警告:Autowired members must be defined in valid Spring bean
    @Autowired
    private CustomerRepository repo;

    @Test
    public void testCustomerSql(){
        // 打印null
        System.out.println(repo);
    }
}

@Autowired上出现一个警告信息:

Autowired members must be defined in valid (@Component|@Service|...) 

运行后,最后打印出的repo是一个null。

我在CustomerTest上标注了@Component(我不知道这样是否合理),@Autowired警告消失了,但是打印的repo还是个null。

我想问:
1. 一般在Java测试类中如何正确的使用JPA。
2. 为什么我在CustomerTest上标注了@Component但打印repo还是null值。

谢谢。

阅读 3.7k
1 个回答

你这样是不行的,这么写 在单元测试中没有spring上下文,有两种办法可以在junit中引入spring上下文:

  1. 手动在测试类中创建ApplicationContext
  2. 通过junit注解引入
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题