web-dev-qa-db-fra.com

Non trouvé pour la dépendance: attend au moins 1 bean qui est considéré comme candidat autowire pour cette dépendance Annotations de dépendance:

J'essaie d'écrire un service SOAP à l'aide de Spring, mais je reçois un problème d'injection de dépendance. J'ai des problèmes pour utiliser @Autowired via le service comme ceci:

    public interface UserDao {
    User getUser(String username);
}

Mise en œuvre pour Dao comme ci-dessous:

  @Controller("userDao")
    public class UserDaoImpl implements UserDao {
    private static Log log = LogFactory.getLog(UserDaoImpl.class);

    @Autowired
    @Qualifier("sessionFactory")
    private LocalSessionFactoryBean sessionFactory;

    @Override
    public User getUser(String username) {
        Session session = sessionFactory.getObject().openSession();
        // Criteria query = session.createCriteria(Student.class);
        Query query = session
                .createQuery("from User where username = :username");
        query.setParameter("username", username);
        try {
            System.out.println("\n Load Student by ID query is running...");
            /*
             * query.add(Restrictions.like("id", "%" + id + "%",
             * MatchMode.ANYWHERE)); return (Student) query.list();
             */
            return (User) query.uniqueResult();
        } catch (Exception e) {
            // TODO: handle exception
            log.info(e.toString());
        } finally {
            session.close();
        }
        return null;
    }

}

et 

public interface UserBo {
    User loadUser(String username);
}

et 

public class UserBoImpl implements UserBo {
    @Autowired
    private UserDao userDao;

    @Override
    public User loadUser(String username) {
        // TODO Auto-generated method stub
        return userDao.getUser(username);
    }

}


@WebService
@Component
public class UserService {

    @Autowired
    private UserBo userBo;

    @WebMethod(operationName = "say")
    public String sayHello(String name) {
        return ("Hello Java to " + name);
    }

    @WebMethod(operationName = "getUser")
    public User getUser(String username) {
        return userBo.loadUser(username);
    }
}

Ce qui suit est un fichier de mapping XML

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ws="http://jax-ws.dev.Java.net/spring/core"
    xmlns:wss="http://jax-ws.dev.Java.net/spring/servlet"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://jax-ws.dev.Java.net/spring/core
    http://jax-ws.Java.net/spring/core.xsd
    http://jax-ws.dev.Java.net/spring/servlet
    http://jax-ws.Java.net/spring/servlet.xsd

    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <context:annotation-config />

    <context:component-scan base-package="edu.Java.spring.ws"></context:component-scan>
    <context:component-scan base-package="edu.Java.spring.ws.dao"></context:component-scan>
    <bean id="userDao" class="edu.Java.spring.ws.dao.UserDaoImpl"></bean>
    <!-- <context:component-scan base-package="edu.Java.spring.ws.bo"></context:component-scan>
     -->
    <wss:binding url="/user">
        <wss:service>
            <ws:service bean="#userService" />
        </wss:service>
    </wss:binding>
    <bean id="userBo" class="edu.Java.spring.ws.bo.impl.UserBoImpl"></bean>
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/contentdb" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan" value="edu.Java.spring.ws.model" />
    </bean>
</beans>

Et l'erreur renvoyée lors du déploiement est la suivante: Voici la trace mise à jour de la pile:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.Sun.xml.ws.transport.http.servlet.SpringBinding#0' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot create inner bean '(inner bean)#538071ba' of type [org.jvnet.jax_ws_commons.spring.SpringService] while setting bean property 'service'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#538071ba' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'userService' while setting bean property 'bean'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.Java.spring.ws.bo.UserBo edu.Java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.Java.spring.ws.dao.UserDao edu.Java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.Java.spring.ws.dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.Java:290)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.Java:129)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.Java:1456)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.Java:1197)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.Java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.Java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.Java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.Java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.Java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.Java:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.Java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.Java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.Java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.Java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.Java:106)
    at org.Apache.catalina.core.StandardContext.listenerStart(StandardContext.Java:4992)
    at org.Apache.catalina.core.StandardContext.startInternal(StandardContext.Java:5490)
    at org.Apache.catalina.util.LifecycleBase.start(LifecycleBase.Java:150)
    at org.Apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.Java:1575)
    at org.Apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.Java:1565)
    at Java.util.concurrent.FutureTask.run(Unknown Source)
    at Java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at Java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at Java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#538071ba' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'userService' while setting bean property 'bean'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.Java.spring.ws.bo.UserBo edu.Java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.Java.spring.ws.dao.UserDao edu.Java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.Java.spring.ws.dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.Java:336)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.Java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.Java:1456)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.Java:1197)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.Java:475)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.Java:276)
    ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.Java.spring.ws.bo.UserBo edu.Java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.Java.spring.ws.dao.UserDao edu.Java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.Java.spring.ws.dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.Java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.Java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.Java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.Java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.Java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.Java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.Java:195)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.Java:328)
    ... 30 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.Java.spring.ws.bo.UserBo edu.Java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.Java.spring.ws.dao.UserDao edu.Java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.Java.spring.ws.dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.Java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.Java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.Java:289)
    ... 38 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.Java.spring.ws.dao.UserDao edu.Java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.Java.spring.ws.dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.Java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.Java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.Java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.Java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.Java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.Java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.Java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.Java:1017)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.Java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.Java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.Java:480)
    ... 40 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.Java.spring.ws.dao.UserDao edu.Java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.Java.spring.ws.dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.Java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.Java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.Java:289)
    ... 51 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.Java.spring.ws.dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.Java:1103)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.Java:963)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.Java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.Java:480)
    ... 53 more
41
user2659694

Regardez l'exception:

No qualifying bean of type [edu.Java.spring.ws.dao.UserDao] found for dependency

Cela signifie qu'il n'y a pas de haricot disponible pour répondre à cette dépendance. Oui, vous avez une implémentation de l'interface, mais vous n'avez pas créé de bean pour cette implémentation. Vous avez deux options:

  • Annotez UserDaoImpl avec @Component ou @Repository et laissez le composant analyser le travail à votre place, exactement comme vous l'avez fait avec UserService.
  • Ajoutez le bean manuellement à votre fichier XML, comme vous l'avez fait avec UserBoImpl.

N'oubliez pas que si vous créez explicitement le bean, vous devez placer la définition avant l'analyse du composant. Dans ce cas, l'ordre est important.

40
diegomtassis

Ajoutez l'annotation @Repository à l'implémentation de UserDaoImpl

@Repository
public class UserDaoImpl implements UserDao {
    private static Log log = LogFactory.getLog(UserDaoImpl.class);

    @Autowired
    @Qualifier("sessionFactory")
    private LocalSessionFactoryBean sessionFactory;

    //...

}
10
Jens

Il semble que l'implémentation de l'interface UserDao soit manquante. Si vous regardez de près l’exception, il est écrit: 

Aucun bean qualifiant de type [edu.Java.spring.ws.dao.UserDao] trouvé pour dépendance:

La façon dont fonctionne @Autowired consiste à rechercher automatiquement la mise en oeuvre d'une dépendance injectée via une interface. Dans ce cas puisqu'il n'y a pas d'implémentation valide de l'interface UserDao, vous obtenez l'erreur.Vérifiez que vous avez une implémentation valide pour cette classe et que votre erreur devrait disparaître.

J'espère que cela pourra aider.

4
Nilesh

J'ai ajouté @Service avant impl class et l'erreur a disparu.

@Service
public class FCSPAnalysisImpl implements FCSPAnalysis
{}
4
Gjorgi Gjorgiev

Nous sommes confrontés à ce problème mais avec une raison différente, voici la raison:

Dans notre projet, nous avons trouvé plusieurs entrées de beans avec le même nom de bean. 1 dans applicationcontext.xml et 1 dans dispatcherServlet.xml

Exemple:  

<bean name="dataService" class="com.app.DataServiceImpl">
<bean name="dataService" class="com.app.DataServiceController">

& nous essayons de nous connecter automatiquement par nom de service de données.

Solution: Nous avons changé le nom du bean & son résolu.

2
Jitendra Nandre

Dans mon cas, le contexte de l'application n'est pas chargé car j'ajoute l'annotation @DataJpaTest. Quand je le change en @SpringBootTest cela fonctionne.

@DataJpaTest charge uniquement la partie JPA d'une application Spring Boot. Dans le JavaDoc: 

Annotation pouvant être utilisée en combinaison avec @RunWith(SpringRunner.class) pour un test JPA typique. Peut être utilisé lorsqu'un test se concentre uniquement sur des composants JPA . L'utilisation de cette annotation désactive la configuration automatique complète et applique à la place uniquement la configuration pertinente pour les tests JPA.

Par défaut, les tests annotés avec @DataJpaTest utilisent une base de données intégrée en mémoire (remplaçant toute source de données explicite ou généralement configurée automatiquement). L'annotation @AutoConfigureTestDatabase peut être utilisée pour remplacer ces paramètres . Si vous souhaitez charger la configuration complète de votre application tout en utilisant une base de données intégrée, vous devez envisager d'associer @SpringBootTest avec @AutoConfigureTestDatabase plutôt que cette annotation.

1
WesternGun

Dans mon cas, j'ai dû déplacer l'annotation @Service de l'interface vers la classe d'implémentation.

1
OAM

Ajoutez une annotation de référentiel avant votre exemple DAO Implementation Class .:

@Repository
public class EmpDAOImpl extends BaseNamedParameterJdbcDaoSupportUAM 
implements EmpDAO{ 
}
0

J'ai manqué d'ajouter 

@Controller("userBo") into UserBoImpl class.

La solution à cela consiste à ajouter ce contrôleur dans la classe Impl.

0
user2659694