找不到依赖项:预计至少有一个bean可以作为此依赖项的autowire候选者。依赖注释:

时间:2014-09-29 08:49:22

标签: java spring web-services soap

我正在尝试使用Spring编写SOAP服务,但是我收到了依赖注入问题。我在使用@Autowired这样的服务时遇到问题:

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

Dao的实施如下:

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

}

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

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

以下是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>

部署时抛出的错误是: 这是更新的堆栈跟踪:

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

14 个答案:

答案 0 :(得分:42)

查看异常:

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

这意味着没有可用于实现该依赖关系的bean。是的,您有一个接口的实现,但您还没有为该实现创建一个bean。您有两种选择:

  • 使用UserDaoImpl@Component注释@Repository,然后让组件扫描为您完成工作,就像使用UserService一样。
  • 将bean手动添加到xml文件中,与UserBoImpl完成相同。

请记住,如果明确创建bean,则需要在组件扫描之前放置定义。在这种情况下,订单很重要。

答案 1 :(得分:11)

将注释@Repository添加到UserDaoImpl

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

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

    //...

}

答案 2 :(得分:5)

我在impl类之前添加了@Service,错误消失了。

@Service
public class FCSPAnalysisImpl implements FCSPAnalysis
{}

答案 3 :(得分:4)

您似乎缺少UserDao接口的实现。如果你仔细看一下例外,就说

  

找不到[edu.java.spring.ws.dao.UserDao]类型的限定bean   依赖性:

@Autowired的工作方式是它会自动查找您通过接口注入的依赖项的实现。在这种情况下,由于没有有效的接口UserDao实现,您会收到错误。确保您拥有此类的有效实现,并且应该出错。

希望有所帮助。

答案 4 :(得分:4)

就我而言,由于我添加了Gson批注,因此未加载应用程序上下文。当我将其更改为@DataJpaTest时,它可以工作。

@SpringBootTest仅加载Spring Boot应用程序的JPA部分。在JavaDoc中:

  

可以与@DataJpaTest结合使用的批注,用于典型的JPA测试。当测试仅关注JPA组件时可以使用。   使用此注释将禁用完全自动配置,而仅应用与JPA测试相关的配置。

     

默认情况下,用@RunWith(SpringRunner.class)注释的测试将使用嵌入式内存数据库(替换任何显式或通常自动配置的数据源)。 @DataJpaTest批注可用于覆盖这些设置。   如果您希望加载完整的应用程序配置,但使用的是嵌入式数据库,则应考虑将@AutoConfigureTestDatabase@SpringBootTest结合使用,而不要使用此注释。

答案 5 :(得分:2)

我们面临这个问题但有不同的原因,原因如下:

在我们的项目中找到了具有相同bean名称的多个bean条目。 applicationcontext.xml&amp;中的1 1在dispatcherServlet.xml中

示例:

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

&安培; 我们正在尝试通过dataService名称进行自动装配。

<强>解决方案: 我们更改了bean名称&amp;它解决了。

答案 6 :(得分:2)

在我的情况下,我不得不将@Service注释从接口移到实现类。

答案 7 :(得分:0)

我错过了添加

@Controller("userBo") into UserBoImpl class.

解决方法是将此控制器添加到Impl类中。

答案 8 :(得分:0)

在DAO实现类之前添加存储库注释。 例如:

@Repository
public class EmpDAOImpl extends BaseNamedParameterJdbcDaoSupportUAM 
implements EmpDAO{ 
}

答案 9 :(得分:0)

请问我有多个原因。但是您可能会忘记为@Autowired做过的组件添加为@Bean。

就我而言,我忘了用@Bean装饰,这导致了此问题。

答案 10 :(得分:0)

就我而言,我具有以下项目结构:

enter image description here

在运行测试时,我一直无法通过auro布线 facade kafka 属性,即使缺少测试和API类位于同一包中。显然那些没有被扫描。

真正有用的是添加 @Import 注释,将缺少的类带到Spring类路径中并使其实例化。

答案 11 :(得分:0)

使用@DataJpaTest时,需要使用@Import显式加载类。它不会为您自动加载。

答案 12 :(得分:0)

我只是解决了我的测试中发生的错误。

只需确保您的测试类在要测试的类的属性中具有所有依赖性,并用@MockBean注释,以便SpringBoot测试上下文可以正确地连接您的类。

(如果您正在测试控制器):您还需要类注释才能正确加载Controller上下文。

签出:

@DisplayName("UserController Adapter Test")
@WebMvcTest(UserController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import(TestConfig.class)
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper;

@MockBean
private CreateUserCommand createUserCommand;

@MockBean
private GetUserListQuery getUserListQuery;

@MockBean
private GetUserQuery getUserQuery;

答案 13 :(得分:0)

对我来说,罪魁祸首是依赖的大小。

一些项目相关的依赖没有正确下载,导致这个错误。与具有类似设置的队友核对并再次添加了罐子。