【问题标题】:Service injection into Controller (Spring MVC)服务注入控制器(Spring MVC)
【发布时间】:2012-04-11 22:44:57
【问题描述】:

您好,我有一个 Spring Web 应用程序,我已经将它构建到控制器阶段,我可以将我的 Daos 注入到我的服务中。现在,当我想将我的服务注入到我的控制器中时,我得到了一个依赖于 Dao 的错误,并进一步降低了 sessionFactory。我不想再次注入这些,因为这最终会导致我最终创建一个数据源,但我有我的 Daos 用于数据访问,他们已经知道 sessionFactory。我在这里遗漏了什么吗?

这里是示例代码 sn-ps:

我的服务:

@Service("productService")
@Transactional
public class ProductServiceImpl implements ProductService {
    private ProductDao productDao;

    @Autowired
    public void setDao(ProductDao productDao) {
        this.productDao = productDao;
    }
}

我的控制器

@Controller
@WebServlet(name="controllerServlet", loadOnStartup=/*...*/, urlPatterns={/*...*/})
public class ControllerServlet extends HttpServlet {
    boolean isUserLogedIn = false;

    @Autowired
    private ProductService productService;

    public void setProductService(ProductService productService){
        this.productService = productService;
    }
}

堆栈跟踪:

 javax.servlet.ServletException: Servlet.init() for servlet mvcServlet threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
         org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
  org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:            565)
     org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1812)
          java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
          java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
        java.lang.Thread.run(Thread.java:662)
            root cause

            org.springframework.beans.factory.BeanCreationException: Error creating                bean with name 'controllerServlet': Injection of autowired dependencies failed; nested   exception is org.springframework.beans.factory.BeanCreationException: Could not autowire   field: private com.phumzile.acme.services.ProductService  com.phumzile.acme.client.web.controller.ControllerServlet.productService; nested exception   is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of   type [com.phumzile.acme.services.ProductService] 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)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.p ostProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)

Servlet-上下文:

<context:component-scan base-package="com.phumzile.acme.client" />
<!-- Enables the Spring MVC @Controller programming model -->
<mvc:annotation-driven />
</beans>

应用配置:

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>configuration.properties</value>
</list>
</property>
</bean>
    <context:annotation-config/> 
<context:component-scan base-package="com.phumzile.acme" />
<import resource="db-config.xml" />
    </beans>

数据库配置

  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close">
    <property name="idleConnectionTestPeriod" value="10800"/>
     <property name="maxIdleTime" value="21600"/>


    <property name="driverClass">
        <value>${jdbc.driver.className}</value>
    </property>
    <property name="jdbcUrl">
        <value>${jdbc.url}</value>
    </property>
    <property name="user">
        <value>${jdbc.username}</value>
    </property>
    <property name="password">
        <value>${jdbc.password}</value>
    </property>

        </bean>
      <bean id="sessionFactory"

          class="org.springframework.orm.hibernate3.a
           nnotation.AnnotationSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
      <property name="annotatedClasses">
        <list>
        <!-- Entities -->
            <value>com.phumzile.acme.model.User</value>
            <value>com.phumzile.acme.model.Person</value>
            <value>com.phumzile.acme.model.Company</value>
            <value>com.phumzile.acme.model.Product</value>
            <value>com.phumzile.acme.model.Game</value>
            <value>com.phumzile.acme.model.Book</value>
        <!-- Entities -->

        </list>
    </property>
    <property name="packagesToScan" value="com.phumzile.acme" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${jdbc.hibernate.dialect
      </prop>
            <prop key="hibernate.hbm2ddl.auto">validate</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>
<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref bean="sessionFactory" />
    </property>

</bean>
<tx:annotation-driven />
    </beans>

CONFIGURATION.PROPERTIES

    jdbc.driver.className=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mydb
    jdbc.username=root
    jdbc.password=root
    jdbc.hibernate.dialect=org.hibernate.dialect.MySQLDialect

【问题讨论】:

  • 这里是示例代码sn-ps
  • 我没有看到任何代码sn-ps...如果没有一些代码可以回答这个问题。
  • 看不到代码,答案取决于你的接线方式。
  • 让我试着用代码编辑问题
  • 您没有提供足够的控制器来查看您是如何连接它的。您能否给我们您尝试将ProductService 连接到您的控制器的代码部分?此外,堆栈跟踪可能会很好。

标签: hibernate jsp spring-mvc


【解决方案1】:

您的 applicationContext.xml 中的组件扫描可能过于广泛。您可能正在双重扫描您的控制器。尝试将其设为&lt;context:component-scan base-package="com.phumzile.acme.services,com.phumzile.acme.repository" /&gt;。 (假设您的 daos 位于存储库包中的某个位置。)

【讨论】:

  • 我已将我的扫描仪更改为您建议的,但仍然出现同样的错误。不过我有一个问题......有谁知道扫描的先验是什么,在主类的上下文和控制器之间,如果有这样的方法,是否有办法改变它。
  • This question 有一些关于组件扫描优先级的好信息。
猜你喜欢
  • 2012-07-08
  • 2012-12-08
  • 2019-06-04
  • 2014-11-06
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多