【发布时间】:2014-05-24 20:58:06
【问题描述】:
我正在使用 Maven、Spring MVC 和 Spring Data Mongo 开发一个小型 Web 应用程序。当我的一个控制器尝试访问自定义存储库中定义的方法时,我收到了 java.lang.NoSuchMethodError。当通过扩展 AbstractJUnit4SpringContextTests 的 JUnit 4 测试并使用几乎相同的 XML 配置文件进行练习时,同样的方法也可以正常工作。
标准存储库:
public interface IndividualRepository extends MongoRepository<Individual, String>, IndividualRepositoryCustom {
...
}
自定义界面:
public interface IndividualRepositoryCustom {
Individual findByIdentifier(String identifierType, String identifierValue);
}
自定义实现:
public class IndividualRepositoryImpl implements IndividualRepositoryCustom {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public Individual findByIdentifier(String identifierType, String identifierValue) {
String locator = String.format("identifiers.%s", identifierType);
return mongoTemplate.findOne(query(where(locator).is(identifierValue)), Individual.class);
}
}
dataaccess-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
<mongo:repositories base-package="com.myco.dataaccess"/>
<mongo:mongo host="mongo.myco.com" port="27017"/>
<mongo:db-factory dbname="test" mongo-ref="mongo"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo"/>
<constructor-arg value="test"/>
</bean>
</beans>
在我的 JUnit 测试中,我有(摘录):
@Autowired
private IndividualRepository individualRepo;
...
List<Individual> foundList = individualRepo.findAll();
assertNotNull(foundList);
assertTrue(foundList.size() > 0);
Individual found = individualRepo.findByIdentifier("someid", "123456");
assertNotNull(found);
assertEquals("Bob", found.getFirstName());
测试通过了,调用了 findAll()(标准 Repository 方法)和 findByIdentifier()(自定义方法)。后者在被 Jetty 中的 Web 应用程序中运行的 Controller 调用时失败并出现 NoSuchMethodError,而同一个 Controller 可以毫无问题地调用 findAll()。
【问题讨论】:
标签: spring maven spring-mvc spring-data-mongodb maven-jetty-plugin