我目前正在使用Spring Data Neo4j开发一个应用程序。这是我第一次使用Spring框架。
但是,自动连接的注释不起作用,我总是得到null。这是代码:
public class CreateDiaryTransaction extends Transaction {
@Autowired
DirayRepository repository;
@Override
public Object perform(Map<String, Object> parameters) {
// TODO Auto-generated method stub
Diary diary = (Diary) DiaryFactory.getInstance().create(parameters);
repository.save(diary);
return diary.toJsonRepre();
}
}
然后我在单元测试中测试它:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "/applicationContext.xml" })
public class CreateDiaryTransactionTest {
@Test
public void test() {
Transaction transaction = new CreateDiaryTransaction();
Map<String, Object> parameters = new HashMap<>();
parameters.put("title", "Test");
parameters.put("weather", "sun");
parameters.put("mood", "happy");
parameters.put("html", "<a href=\"javascript:void(0)\">link</a>");
parameters.put("images", new ArrayList<Image>());
try {
transaction.execute(parameters);
} catch (Exception e) {
fail("Exception occur");
}
}
}
当我运行它时,我得到了null对象异常。但是,当我将存储库直接放在单元测试中时,它工作正常。这是另一个有效的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "/applicationContext.xml" })
public class DiaryRepositoryTest {
@Autowired
DirayRepository repository;
@Test
@Transactional
public void testSaveDiary() {
Diary diary = (Diary) DiaryFactory.getInstance().create(
new HashMap<String, Object>());
repository.save(diary);
Diary retrivedDiary = repository.findOne(diary.getGraphId());
assertEquals(diary, retrivedDiary);
}
}
这是我的应用程序上下文:
<context:annotation-config />
<neo4j:config storeDirectory="target/data/pamela"
base-package="com.bond.pamela.domain" />
<neo4j:repositories base-package="com.bond.pamela.persistence" />
<tx:annotation-driven mode="aspectj" />
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean
class="com.bond.pamela.domain.valueObject.converter.ImageToJsonConverter" />
<bean
class="com.bond.pamela.domain.valueObject.converter.JsonToImageConverter" />
</set>
</property>
</bean>
我想我以某种方式将存储库放在spring上下文之外,但是我怎么能得到它呢? THX
答案 0 :(得分:1)
您需要在申请环境中关注
<context:component-scan base-package="packagename.package" />
此处包名称是包含所有带注释的类的包。
请看这篇文章了解更多信息:
Spring MVC: Difference between context:annotation-config vs context:component-scan
答案 1 :(得分:0)
确保您已在@Repository
的实施中编写了@Component
或DirayRepository
注释,并且您已编写了组件扫描
applicationContext.xml
DirayRepository
@Repository
public class DirayRepositoryImpl implements DirayRepository {
void save() { ...}
}