Spring控制器中的自动bean注入

时间:2014-02-18 11:16:40

标签: java spring

无法弄清楚,出了什么问题。我一次又一次地得到同样的错误。我搜索过Google但未能解决此问题。我在这里寻找相同的帖子尝试解决但仍然相同。

JobsDAOImp.java

public class JobsDAOImp implements JobsDAO {

    @Autowired 
    private SessionFactory sessionFactory;
        ..        
}

JobService.java

public interface JobsService {
       ....
}

JobServiceImp.java

@Service
@Transactional(readOnly=true)
public class JobsServiceImp implements JobsService {

    @Autowired private JobsDAOImp jobsDAOImp;
        ..
}

JobsController.java

@Controller
@RequestMapping(value="/")
public class JobsController {

    @Autowired
    private JobsService jobsService;
            ...
}

spring.xml

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

        <context:annotation-config/>        

        <!-- DAO Implementations -->
        <bean id="usersImp" class="org.delance.daoimplementation.UsersImp" />
        <bean id="jobsDAOImp" class="org.delance.daoimplementation.JobsDAOImp" />

        <!-- Service Implementations -->
        <bean id="jobsServiceImp" class="org.delance.serviceimp.JobsServiceImp" />  

        <bean id="dataSource" class="${jdbc.dataSource}" destroy-method="close">
               <property name="driverClass" value="${jdbc.driverClass}"/>
               <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
               <property name="user" value="${jdbc.user}"/>
               <property name="password" value="${jdbc.password}"/>
               <property name="maxStatements" value="${jdbc.maxStatements}"/>

               <property name="acquireIncrement" value="${jdbc.acquireIncrement}" />                   

               <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}" />  
               <property name="checkoutTimeout" value="${jdbc.checkoutTimeout}" /> 
               <property name="unreturnedConnectionTimeout" value="${jdbc.unreturnedConnectionTimeout}" /> 
               <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
               <property name="minPoolSize" value="${jdbc.minPoolSize}" />
               <property name="automaticTestTable" value="${jdbc.automaticTestTable}" /> 
               <property name="testConnectionOnCheckin" value="${jdbc.testConnectionOnCheckin}" />                 
        </bean>

        <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
               <property name="dataSource" ref="dataSource"/>

               <property name="packagesToScan">
                            <array>
                               <value>org.delance.models</value>
                            </array>
               </property>               

               <property name="hibernateProperties">
                 <value>
                   hibernate.dialect = org.hibernate.dialect.MySQLDialect
                   hibernate.cache.provider_class = org.hibernate.cache.NoCacheProvider
                   hibernate.show_sql = true
                   hibernate.hbm2ddl.auto = create
                 </value>
               </property>               

        </bean>                

        <context:property-placeholder location="application.properties" />
</beans>    

MVC-调度-servlet.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:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <mvc:annotation-driven />

    <context:component-scan base-package="org.delance" />

    <bean id="multipartResolver"
           class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

    <mvc:resources mapping="/**" location="/" />            

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="cacheSeconds" value="0" />
    </bean>

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

遇到此问题: -

    SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobsController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.delenace.service.JobsService org.delenace.controllers.JobsController.jobsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.delenace.service.JobsService] 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:289)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:656)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1635)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.delenace.service.JobsService org.delenace.controllers.JobsController.jobsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.delenace.service.JobsService] 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:517)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
    ... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.delenace.service.JobsService] 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:988)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
    ... 28 more

Feb 18, 2014 5:01:17 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobsController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.delenace.service.JobsService org.delenace.controllers.JobsController.jobsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.delenace.service.JobsService] 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:289)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:656)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1635)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.delenace.service.JobsService org.delenace.controllers.JobsController.jobsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.delenace.service.JobsService] 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:517)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
    ... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.delenace.service.JobsService] 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:988)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489)
    ... 28 more

4 个答案:

答案 0 :(得分:6)

使用接口而不是JobsController中的实现,因为spring为JobServiceImpl bean生成了一个java代理,而java代理基于接口。

 @Autowired
 private JobsService jobsService;

答案 1 :(得分:1)

我没有看到你的整个项目以及确切的配置是什么,但在我看来你只加载没有spring.xml的mvc-dispatcher-servlet.xml。在你的情况下,这是正常的,因为你已经定义了

<context:component-scan base-package="org.delance" />

扫描bean定义。因此,假设您只加载了mvc-dispatcher-servlet.xml,您应该检查控制器和服务是否都在具有此公共基础包“org.delance”的包中,否则spring类路径扫描将不会选择它们起来。你也应该摆脱限定符 - 这是因为你有两个或更多给定类型的bean。 无论如何,我以前遇到过这种问题,我相信它会变小。

关于你有两个配置(或者也有上下文)的事实,你需要考虑更多的事情。您不应该定义一个bean两次(一次通过包扫描,第二次在xml配置中),除非故意这样做。如果您解决了第一个问题,那么当您加载两个上下文(spring.xml和mvc-dispatcher-servlet.xm)时,您将遇到其他问题

答案 2 :(得分:0)

您需要将jobService.java类设置为bean。像@Component一样添加立体声类型注释。

答案 3 :(得分:0)

如果你使用这样的定义:

<bean id="jobsServiceImp" class="org.delance.serviceimp.JobsServiceImp" />

你没有利用Spring Dependency Injection功能,因为接口和实现类之间没有区别;在Spring中,您可能希望在整个代码中使用接口并在应用程序上下文配置中声明它们的实现(这被定义为关注点分离);如果您决定更改实现,这也很有用,因为您只需要更改xml配置。

请尝试以下方法:

<bean id="jobsService" class="org.delance.serviceimp.JobsServiceImp" />

的Salvatore