今天写完代码做单元测试的时候,service老注入不进去
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext-*.xml");
ItemLocationService itemLocationService = (ItemLocationService) context.getBean(ItemLocationServiceImpl.class);
Map<String,String> numberMap= itemLocationService.findAllLocationNumber("E20181025093345020300016");
for (Map.Entry<String, String> entry : numberMap.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
看了配置文件一切扫描包什么都配了,没有发现异常,就检查service,发现有一个@Transactional注解。就网上搜一下,发现这篇文章,去除注解后,确实可以正常运行,但还是不了解原因,继续深入查找,发现这篇文章。
在applicationContext里加入了
<aop:aspectj-autoproxy proxy-target-class="true"/>
以及在pom里新增3个依赖
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.12</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.12</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency>
就可以注入成功了。
大概是因为代理模式的不同。默认jdk动态代理,这里强制使用cglib代理。先记住原因和解决方法