@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值。
谢谢。
回答:
你这样是不行的,这么写 在单元测试中没有spring上下文,有两种办法可以在junit中引入spring上下文:
- 手动在测试类中创建ApplicationContext
- 通过junit注解引入
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
以上是 @Autowired只能在Bean中使用吗? 的全部内容, 来源链接: utcz.com/p/944428.html