因此,我有一个使用spring ne4j的项目,遇到了一个不太清楚的问题。对于Spring-ne4j,Neo4jConfig.java,我使用java配置:
@Configuration
@EnableNeo4jRepositories(basePackages = "org.neo4j.example.repository")
@EnableTransactionManagement
public class Neo4jConfig extends Neo4jConfiguration {
@Bean
public SessionFactory getSessionFactory() {
// with domain entity base package(s)
return new SessionFactory("org.neo4j.example.domain");
}
// needed for session in view in web-applications
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
return super.getSession();
}
}
I有一个DAO和一个工具,BeanDaoImpl.java:
@Repository
public class BeanDaoImpl implements BeanDao {
public String getStr() {
return "from BeanImpl";
}
}
然后我有一个使用DaoImpl的服务,注意到自动发色的是BeanDaoImpl,而不是BeanDao
@Service
public class MyBeanService {
@Autowired
private BeanDaoImpl daoImpl;
public String getServiceString(){
return daoImpl.getStr();
}
}
下面是我的app-context.xml:
<context:component-scan base-package="com.springconflict" />
该版本是SpringFramework4.2.5,spring new4j4.1.11,似乎spring neo4j与Spring4.2.5兼容;
以下是编译错误信息:
由: org.springframework.beans.factory.BeanCreationException:无法自动生成字段引起:私有com.springconflict.service.MyBeanService.daoImpl;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:,没有找到com.springconflict.dao.impl.BeanDaoImpl类型的限定bean :期望至少有一个bean,它可以作为该依赖项的自动选择。依赖性注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
可能是我删除了Neo4jConfig
,或者使用了测试可以通过的@Autowired BeanDao
。另外,我使用了一个普通的@Configuration
类,测试仍然通过,所以问题可能在Neo4jConfiguration
中出现,有人能告诉我为什么以及如何解决这个问题吗?在实际项目中,我无法将@Autowired BeanDaoImpl
更改为@Autowired BeanDao
。
发布于 2018-09-10 03:06:26
TL;DR答案:在Neo4jConfig
中定义以下附加bean,从而覆盖SDN4.x的默认PersistenceExceptionTranslationPostProcessor
实例。
@Bean
PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
PersistenceExceptionTranslationPostProcessor p = new PersistenceExceptionTranslationPostProcessor();
p.setProxyTargetClass(true);
return p;
}
长答案: Spring Data Neo4j使用Spring PersistenceExceptionTranslationPostProcessor
将Neo4j OGM异常重新映射为Spring数据异常。这些处理器应用于@Repository
类型的所有组件。
因此,后处理器现在在您的BeanDoaImpl
周围形成一个代理,因此它基本上类似于另一个类。如果您使用接口,这会很好,但如果您希望将bean分配给具体的类,则不会。
Spring可以被全局配置为创建子类,而不是标准的基于Java接口的代理(它是通过使用CGLIB实现的),但这在默认情况下是不存在的,对于Spring4.2.x和Spring数据,Neo4j 4.2.x也无关紧要,因为上面的post处理器独立于该机制。
用一个显式配置的替换它可以解决您的问题。
从体系结构的角度来看(或者从代码的角度来看),最好是注入接口,而不是具体的类。
请让我知道,如果我能帮你:)
https://stackoverflow.com/questions/51230940
复制相似问题