0
votes
@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");
    }
}

When inject this RoleRepo roleRepo in SecurityServiceImpl I face this error.

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)}

my spring context file

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


my Role class

     @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
Do both class and interface exist in same package?kann
What happens when you annotate RoleRepo with @Repository instead of @Component ?S B
@SB when I used Repository instead of component error message not changed.Yasin
@kann These classes is not same package bu I am scanning with using <context:component-scan base-package=""> tagYasin
Show your Role Entity code as well, make sure it does contain @EntitySwarit Agarwal

2 Answers

0
votes

First of all need to know that the error what says, lets translate that what the error says:

For example:

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

That is says trying to inject a bean that is not defined and the cause is that the required bean is not defined in the Spring Context, and you get this error message.

expected at least 1 bean which qualifies as autowire candidate.

Your desired bean does not exist in the context of the desired bean correctly annotated as a bean (@Component, @Respository, @Service, etc), that is maybe defined in a package that is not scanned by Spring.

So, as we can see there is no definition for bean id of your roleRepo in context file configuration.

0
votes

When using what we call InstantRepository, you must NOT use the annotation @Component. You just have to create a simple Interface, that's it:

public interface RoleRepo extends JpaRepository<Role, Long> {

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

Spring will detect automatically that it has to create an implementation of this interface with a Proxy to execute to desire behaviour. Also, make sure your package is being scanned anyway.