Spring Неудовлетворенная зависимость с данными Spring - PullRequest
0 голосов
/ 10 февраля 2020
@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");
    }
}

При внедрении этого RoleRepo roleRepo в SecurityServiceImpl я сталкиваюсь с этой ошибкой.

org.springframework.beans.factory.UnsatisfiedDependencyException: Ошибка при создании компонента с именем securityServiceImpl ': Неудовлетворенная зависимость выражается через поле' roleRepo '; вложенное исключение - org.springframework.beans.factory.NoSuchBeanDefinitionException: нет доступного квалифицирующего компонента типа com.tk.emd.ui.service.RoleRepo: ожидается как минимум 1 компонент, который считается кандидатом на автопровод. Аннотации зависимостей: {@ org.springframework.beans.factory.annotation.Autowired (обязательно = true)}

мой контекстный файл пружины

   <?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;
    }
}

Ответы [ 2 ]

0 голосов
/ 10 февраля 2020

При использовании того, что мы называем InstantRepository, вы НЕ должны использовать аннотацию @Component. Вам просто нужно создать простой интерфейс, вот и все:

public interface RoleRepo extends JpaRepository<Role, Long> {

    @Query("from Role ro order by ro.name")
    List<Role> getRoles();   
}

Spring автоматически обнаружит, что ему нужно создать реализацию этого интерфейса с прокси-сервером для выполнения по желанию поведения. Кроме того, убедитесь, что ваш пакет сканируется в любом случае.

0 голосов
/ 10 февраля 2020

Прежде всего нужно знать, что ошибка говорит о том, что давайте переведем то, что говорит ошибка:

Например:

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

Это означает, что попытка ввести бин, который не определен, и причина в том, что требуемый компонент не определен в контексте Spring, и вы получаете это сообщение об ошибке.

expected at least 1 bean which qualifies as autowire candidate.

Ваш нужный компонент не существует в контексте правильно аннотированного требуемого компонента как bean-компонент (@Component, @Respository, @Service, et c), который может быть определен в пакете, который не сканируется Spring.

Итак, как мы видим, не существует определения для идентификатор bean-компонента вашей roleRepo в конфигурации файла контекста.

...