【问题标题】:JUnit spring can't inject related beans that located in other project using @AutowiredJUnit spring 无法使用@Autowired 注入位于其他项目中的相关bean
【发布时间】:2017-12-25 12:26:14
【问题描述】:

我在 Spring 项目中工作,我想使用 JUnit 创建一个单元测试,但我得到空指针异常,这是我的代码:

我在我的项目 (A) 中创建测试:

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = {"classpath*:**/applicationContext.xml"})
public class EditionArticleTest {

 @Autowired
 private ArticleService articleService ;

@Test
    public void testfindArticleByNum()
        throws Exception
    {

    //this line return null pointer Exception
     Article article =  articleService.findArticle("AA0045");
   }

}

问题是我的服务的实现依赖于位于其他项目 (B) 中的 bean,如下所示:

public class ArticleServiceImpl implements articleService {

//the implementation of this bean exists in an other project
 private ArticleFinder articleFinder ;

}

所以我在这一行得到了错误:

 @Override
    public Article findArticle( String numArticle )
    {
       //iget the null pointer exception in this line because spring can't 
       //instantiate the beans articleFinder 
        return articleFinder.findByNumArticle( numArticle );
    }

请问您有什么建议可以解决这个问题并强制 spring 自动注入位于其他项目中的所有相关 bean。

问候。

【问题讨论】:

  • 其他项目有办法导入它的bean吗?像@Configuration class 什么的?我认为这是因为 spring 没有扫描其他项目的 bean。您可以发布您的applicationContext.xml 文件吗?
  • 嗨@GuySmorodinsky 谢谢你的时间,是的,每个项目都有它的applicationContext.xml 所以我的项目(A)无法扫描项目(B)中的applicationContext.xml 所以这就是为什么它找不到 bean

标签: java spring spring-mvc junit


【解决方案1】:

您有几个选择。
1. 您可以模拟那些您不需要的依赖项并使用@InjectMocks 注入依赖的类并模拟那些被调用的类的行为和方法
2. 您可以在 applicationContext.xml 中包含您需要的所有 bean,也可以使用
@ContextConfiguration(classes = {abc.class, def.class})

仅包含所需的类

【讨论】:

  • 嗨@pvpkiran,谢谢你的时间,我更喜欢选项2,请你知道如何扫描项目(A)的applicationContext.xml和项目的applicationContext.xml (B) 同时使用@ContextConfiguration?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 2015-12-19
  • 1970-01-01
  • 2013-08-31
  • 2012-01-19
  • 2018-07-19
  • 1970-01-01
相关资源
最近更新 更多