java - Spring对Spring数据的依赖不满足

标签 java spring dependency-injection spring-data-jpa

@Component
public interface RoleRepo extends JpaRepository<Role, Long> {
    @Query("from Role ro order by ro.name")
    List<Role> getRoles();  
}
<小时/>
@Service
@Component
public class SecurityServiceImpl  {

    @Autowired
    RoleRepo roleRepo;

    @PostConstruct
    public void init() {
        System.out.println(roleRepo);
    }

    public SecurityServiceImpl (){
        System.out.println("SecurityServiceImpl created");
    }
}

当在 SecurityServiceImpl 中注入(inject)此 RoleRepo roleRepo 时,我遇到此错误。

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityServiceImpl': Unsatisfied dependency expressed through field 'roleRepo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tk.emd.ui.service.RoleRepo' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我的 spring 上下文文件

   <?xml version="1.0" encoding="UTF-8"?>
  <beans:beans
xmlns="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing 
    infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
    up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
    in the /WEB-INF/views directory -->
<beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean
    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonMessageConverter" />
        </beans:list>
    </beans:property>
</beans:bean>

<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter"
    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>

<!-- Create DataSource Bean -->

<beans:bean id="dbDataSource"
    class="org.springframework.jndi.JndiObjectFactoryBean">
    <beans:property name="jndiName"
        value="java:comp/env/jdbc/EmdDS" />
</beans:bean>


<jee:jndi-lookup id="dbDataSource" jndi-name="EmdDS"
    expected-type="javax.sql.DataSource" />

<!-- using JEE namespace for lookup -->
<!-- <jee:jndi-lookup id="dbDataSource" jndi-name="jdbc/MyLocalDB" expected-type="javax.sql.DataSource" 
    /> -->

<context:component-scan
    base-package="com.example.jpa.hibernate" />


<!-- Hibernate 3 Annotation SessionFactory Bean definition -->
<beans:bean id="hibernate3AnnotatedSessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <beans:property name="dataSource" ref="dbDataSource" />
    <beans:property name="annotatedClasses">
        <beans:list>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect
            </beans:prop>
            <beans:prop key="hibernate.current_session_context_class">thread</beans:prop>
            <beans:prop key="hibernate.show_sql">false</beans:prop>
            <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
        </beans:props>
    </beans:property>

</beans:bean>

<小时/>

我的角色类别

     @Entity
            @Table(name = "A_ROLE")
            @NamedQuery(name = "Role.findAll", query = "SELECT f FROM Role f")
public class Role extends AbstractModel {
    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name = "ROLE_ID_GENERATOR", sequenceName = "ROLE_SEQ", allocationSize = 1, initialValue = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ROLE_ID_GENERATOR")
    private Long id;

    private String description;

    private String name;

    // bi-directional many-to-one association to FrtUserRole
    @OneToMany(mappedBy = "role", orphanRemoval = true)
    private Set<UserRole> userRoles = new LinkedHashSet<UserRole>();

    public Role() {
    }

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<UserRole> getUserRoles() {
        return userRoles;
    }

    public void setUserRoles(Set<UserRole> userRoles) {
        this.userRoles = userRoles;
    }

    @SuppressWarnings("unchecked")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return name;
    }
}

最佳答案

首先需要知道错误的内容,让我们翻译一下错误的内容:

例如:

 NoSuchBeanDefinitionException: No qualifying bean of type 'com.tk.emd.ui.service.RoleRepo' 

也就是说,尝试注入(inject)一个未定义的 bean,原因是所需的 bean 未在 Spring Context 中定义,并且您会收到此错误消息。

expected at least 1 bean which qualifies as autowire candidate.

您所需的 bean 不存在于正确注释为 bean(@Component、@Respository、@Service 等)的所需 bean 的上下文中,这些 bean 可能是在 Spring 未扫描的包中定义的。

因此,正如我们所看到的,在上下文文件配置中没有定义 roleRepo 的 bean id。

关于java - Spring对Spring数据的依赖不满足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60142724/

相关文章:

java - 优先级

java - 如何在 Java 中向 AKKA 集群中的所有参与者广播消息?

java - 在 tomcat v 8.5 上部署 spring boot 应用程序失败

c# - ASP.NET Core 类型化客户端中的 IHttpClientFactory

c# - 将 IoC 容器作为依赖项注入(inject)有多糟糕?

hibernate - 使用 EJB 注入(inject) EntityManager

java - 如何使用 Wix 创建 Java 应用程序的快捷方式

java - 将文件扫描到字节数组时出现 ArrayIndexOutOfBoundsException

java - 使用 SpringJUnit4ClassRunner 和 Mockito 将模拟对象注入(inject)到 Aspect 类中

java - 在 Spring boot 中从任意 bean 访问 EntityMamanger