【发布时间】:2023-03-12 20:45:01
【问题描述】:
当我尝试自动装配扩展 CrudRepository 的接口时出现此错误。我有两个用于 2 个数据库的休眠 xml 配置。完整的堆栈是
org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“helloController”的bean时出错:通过字段“stockService”表示的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“com.publishing.test.stock.services.StockService”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)} org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url"></property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">100</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQL95Dialect</property>
<!-- Disable the second-level cache -->
<!--<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>-->
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop the existing table and create new one -->
<property name="hbm2ddl.auto">update</property>
<property name="packagesToScan">com.publishing</property>
<!-- Mention here all the model classes -->
<mapping class="com.publishing.models.Stock"/>
</session-factory>
@Controller
public class HelloController {
@Autowired
private StockService stockService;
我在 Spring Config 中也有 3 行
<context:component-scan base-package="com.publishing" />
<context:annotation-config />
<jpa:repositories base-package="com.publishing" />
服务是
@Service("StockService")
public interface StockService extends CrudRepository<Stock, Long> {
编辑:
好的,现在我们已经编辑了hibernate.cfg.xml
<!-- Drop the existing table and create new one -->
<property name="hbm2ddl.auto">update</property>
<!--<property name="packagesToScan">com.publishing</property>-->
<!-- Mention here all the model classes -->
<mapping class="com.publishing.models.Stock"/>
还有服务
@Service("stockService")
public interface StockService extends CrudRepository<Stock, Long> {
【问题讨论】:
-
这是因为你的 bean/service 应该与控制器中的实例命名完全相同,它是区分大小写的。
-
我做了,还是一样的错误
-
能否请您在您的项目中显示扫描包配置?
-
现在它说“无法自动装配 StockService 类型的 bean 不止一个”扫描包?!你是这个意思?!
-
是的,我就是这个意思。我希望这就是您的服务所在的软件包?
标签: java spring dependency-injection dependencies spring-data-jpa