Spring 测试的自动装配问题

发布于 12-15 15:52 字数 3433 浏览 2 评论 0原文

我花了几个小时试图找出为什么我的代码会抛出以下异常。在这一点上,我希望有人能比我更聪明,因为我正在失去希望......;)

原因:org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到依赖项的 [com.ls.forecast.jpa.ForecastElementService] 类型的匹配 bean:预计至少有 1 个有资格作为此依赖项的自动装配候选者的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)、@org.springframework.beans.factory.annotation.Quali fier(值=主)} 在org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924) 在org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793) 在org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707) 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)

我看过很多线程/教程,但没有运气。他们的设置似乎都和我的一样。我在服务的实现上添加了@Service,添加了一个限定符,检查ForecastElementServiceImpl实际上实现了ForecastElementService接口。

服务接口:

public interface ForecastElementService {

Collection<ForecastElement> retrieve(String date);
Collection<ForecastElement> retrieve();
}

接口实现:

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Repository("forecastElementService")
@Service
public class ForecastElementServiceImpl implements ForecastElementService {

@PersistenceContext
protected EntityManager em;

@Override
@Cacheable("forecastElements")
public Collection<ForecastElement> retrieve(String date) {
    String sql = null;
    if(date != null) {
        sql = " SELECT fe FROM ForecastElement fe JOIN FETCH fe.forecastType WHERE ?1 between fe.startDate and fe.endDate";
    } else {
        sql = " SELECT fe FROM ForecastElement fe JOIN FETCH fe.forecastType";
    }
    final TypedQuery<ForecastElement> query = em.createQuery(sql, ForecastElement.class);

    return query.getResultList();
}

@Override
@Cacheable("forecastElements")
public Collection<ForecastElement> retrieve() {

    return retrieve(null);
}

}

context.xml:

<bean id="forecastElementService" class="com.ls.forecast.jpa.ForecastElementServiceImpl">
<property name="entityManagerFactory" ref="entityManagerFactory"/>

最后是故障测试类——forecastElementService 变量是抛出异常的变量。

@Repository
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"*-context.xml"})
public class ModelJpaTest extends AbstractTransactionalJUnit4SpringContextTests {

//final Logger logger = LoggerFactory.getLogger(ModelJpaTest.class);

@Autowired
protected ForecastElementService forecastElementService;

@Autowired
@Qualifier("basicDataSource")
@Override
public void setDataSource(DataSource dataSource) {
    super.setDataSource(dataSource);
}

@Test
public void LoadModelTest() {
    assertNotNull("forecastElementService is null", forecastElementService);
    Collection<ForecastElement> elements = forecastElementService.retrieve();
    assertTrue(elements.size() > 0);
}

}

任何见解或帮助将不胜感激!

请参阅@ContextConfiguration...如果我将 ModelJpaTest-context.xml 放在我的 Maven 项目的资源(测试)文件夹中并编辑为:

@ContextConfiguration({"/ModelJpaTest-context.xml"})

现在真的很困惑...

I have spent hours trying to figure out why my code will thow the following exception. At this point, I am hoping that someone can be more clever than I am as I am losing hope... ;)

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.ls.forecast.jpa.ForecastElementService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Quali
fier(value=main)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)

I have looked at many threads/tutorials without luck. They all seem to have the same set up as mine. I added @Service on the implementation of the service, I added a Qualifier, checked that ForecastElementServiceImpl actually implemented the interface ForecastElementService.

Service interface:

public interface ForecastElementService {

Collection<ForecastElement> retrieve(String date);
Collection<ForecastElement> retrieve();
}

interface implementation:

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Repository("forecastElementService")
@Service
public class ForecastElementServiceImpl implements ForecastElementService {

@PersistenceContext
protected EntityManager em;

@Override
@Cacheable("forecastElements")
public Collection<ForecastElement> retrieve(String date) {
    String sql = null;
    if(date != null) {
        sql = " SELECT fe FROM ForecastElement fe JOIN FETCH fe.forecastType WHERE ?1 between fe.startDate and fe.endDate";
    } else {
        sql = " SELECT fe FROM ForecastElement fe JOIN FETCH fe.forecastType";
    }
    final TypedQuery<ForecastElement> query = em.createQuery(sql, ForecastElement.class);

    return query.getResultList();
}

@Override
@Cacheable("forecastElements")
public Collection<ForecastElement> retrieve() {

    return retrieve(null);
}

}

context.xml:

<bean id="forecastElementService" class="com.ls.forecast.jpa.ForecastElementServiceImpl">
<property name="entityManagerFactory" ref="entityManagerFactory"/>

AND finally the trouble test class - the forecastElementService variable is the one throwing the exception.

@Repository
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"*-context.xml"})
public class ModelJpaTest extends AbstractTransactionalJUnit4SpringContextTests {

//final Logger logger = LoggerFactory.getLogger(ModelJpaTest.class);

@Autowired
protected ForecastElementService forecastElementService;

@Autowired
@Qualifier("basicDataSource")
@Override
public void setDataSource(DataSource dataSource) {
    super.setDataSource(dataSource);
}

@Test
public void LoadModelTest() {
    assertNotNull("forecastElementService is null", forecastElementService);
    Collection<ForecastElement> elements = forecastElementService.retrieve();
    assertTrue(elements.size() > 0);
}

}

Any insight or help would be immensely appreciated!

See @ContextConfiguration... If I place the ModelJpaTest-context.xml in the resource (test) folder of my maven project and edit to:

@ContextConfiguration({"/ModelJpaTest-context.xml"})

Really confused by now...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱她像谁2024-12-22 15:52:06

我需要将注释配置和组件扫描添加到 applicationContext.xml 中,以便正确“自动装配”bean。完成此操作后,我就能够删除测试类 (forecastElementService) 中的变量。

I need to add the annotation config and the component scan to the applicationContext.xml so that it would properly "autowire" the bean. Once this was done, I was able to get rid of the variable in the test class (forecastElementService).

↙厌世2024-12-22 15:52:06

我建议在您的服务实现类上使用 @Repository 或 @Service,但不能同时使用两者。

您可能会遇到与事务未触发相关的另一个问题 - 这里:https://jira.springsource.org /browse/SPR-5082 - 解决方法是在应用程序上下文 xml 定义文件中定义 beans。

I would suggest using either @Repository or @Service - but not both - on your service impl class.

You might run into another problem related to transactions not firing - here: https://jira.springsource.org/browse/SPR-5082 - a work around is to define beans in the application context xml definition file.

三生路2024-12-22 15:52:06

至少您的实现类中没有适当的“entityManagerFactory”。不确定这是否已经导致问题。
您可以分享完整的堆栈跟踪(包括嵌套异常)和 *context.xml 文件的更多片段吗?

编辑:看看这个答案:针对 Java EE 6 API 进行测试

At least there is no propery 'entityManagerFactory' in your implementation class. Not sure if this may already cause the problem.
Can you share the complete stacktrace (including nested exceptions) and some more snippets of the *context.xml file?

EDIT: Have a look at this answer: Testing against Java EE 6 API

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文