服务类中的Spring自动异常

时间:2011-12-24 09:52:22

标签: java spring spring-mvc autowired

我是Spring的新手。我试图在我们的项目中使用autowired。但我在服务类中面临一个问题。 我的服务类:

package com.x.y.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.x.y.dao.RegionDao;
import com.x.y.util.model.Region;

@Service("regionService")
public class RegionServiceImpl implements RegionService{
@Autowired
RegionDao regionDao;

    public List<Region> getAllCities() {
        return regionDao.getAllCities();
    }

}

我的Dao课程:

package com.x.y.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;

import com.x.y.util.model.Region;

@Repository("regionDao")
public class RegionDaoImpl{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Region> getAllCities(){
        StringBuffer strbuf = new StringBuffer();
        try{
            strbuf.append(" SELECT REGION_ID,REGION_NAME,REGION_TYPE_ID,ST_AsText(THE_GEOM) AS geom FROM REGION WHERE REGION_TYPE_ID = 1");


            SqlRowSet rowset = jdbcTemplate.queryForRowSet(strbuf.toString());
            Region region = null;
            List<Region>regions = new ArrayList<Region>();
            while(rowset.next()){
                region = new Region();
                region.setRegionId(rowset.getLong("REGION_ID"));
                region.setRegionName(rowset.getString("REGION_NAME"));
                region.setRegionTypeId(rowset.getInt("REGION_TYPE_ID"));
                regions.add(region);
            }
             return regions;
            }catch(Exception e){
                return null;
            }
    }
}

的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>xy.in</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
            /WEB-INF/test-*.xml
         </param-value>
  </context-param>
  <filter>
    <filter-name>encoding-filter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encoding-filter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter>
    <filter-name>GzipFilter</filter-name>
    <filter-class>com.cj.gzipflt.GzipFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>GzipFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>GzipFilter</filter-name>
    <url-pattern>*.htm</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>GzipFilter</filter-name>
    <url-pattern>*.css</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>GzipFilter</filter-name>
    <url-pattern>*.jpg</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>GzipFilter</filter-name>
    <url-pattern>*.gif</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>GzipFilter</filter-name>
    <url-pattern>*.js</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>GzipFilter</filter-name>
    <url-pattern>*.png</url-pattern>
  </filter-mapping>

  <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>test</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>test</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>
            org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>
  <jsp-config>
    <taglib>
      <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
      <taglib-location>/WEB-INF/tld/c.tld</taglib-location>
    </taglib>
    <taglib>
      <taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>
      <taglib-location>/WEB-INF/tld/fmt.tld</taglib-location>
    </taglib>
  </jsp-config>
  <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/jsp/pageNotFound.jsp</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/jsp/pageNotFound.jsp</location>
  </error-page>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
</web-app>

测试servlet.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
     xmlns:task="http://www.springframework.org/schema/task"
    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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
        http://www.springframework.org/schema/task
   http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    <context:component-scan base-package="com.x.y.web.controller" />
    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
        p:paramName="locale" />

    <!-- Declare the Resolver -->
    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages/bizmaps" />
        <property name="cacheSeconds" value="1" />
        <property name="useCodeAsDefaultMessage" value="true" />
    </bean>

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

    <bean id="xmlFileViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">

        <property name="location">

            <value>/WEB-INF/views.xml</value>

        </property>

        <property name="order">

            <value>1</value>

        </property>

    </bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <entry key="htm" value="text/html" />
                <entry key="json" value="application/json" />

            </map>
        </property>
        <property name="viewResolvers">
            <list>
                <bean id="internalView"
                    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="viewClass"
                        value="org.springframework.web.servlet.view.JstlView" />
                    <property name="prefix" value="/WEB-INF/jsp/" />
                    <property name="suffix" value=".jsp" />
                    <property name="order">
                        <value>1</value>
                    </property>
                </bean>
            </list>
        </property>
        <property name="defaultViews">
            <list>
                <bean
                    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
                    <property name="prefixJson" value="true" />
                </bean>
            </list>
        </property>
    </bean>


<!-- JSON configuration for arabic support -->
    <bean name="jsonView" class="org.springframework.web.servlet.view.json.JsonView">
        <property name="encoding">
            <value>UTF-8</value>
        </property>
        <property name="contentType">
            <value>application/json</value>
        </property>
        <property name="jsonWriter">
            <ref bean="sojoJsonWriter" />
        </property>
        <property name="jsonErrors">
            <list>
                <ref bean="statusError" />
                <ref bean="modelflagError" />
            </list>
        </property>
    </bean>
    <bean id="jsonView2" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
    <bean name="sojoJsonWriter"
        class="org.springframework.web.servlet.view.json.writer.sojo.SojoJsonStringWriter">
        <property name="convertAllMapValues">
            <value>false</value>
        </property>
    </bean>

    <bean name="statusError"
        class="org.springframework.web.servlet.view.json.error.HttpStatusError">
        <property name="errorCode">
            <value>311</value>
        </property>
    </bean>

    <bean name="modelflagError"
        class="org.springframework.web.servlet.view.json.error.ModelFlagError">
        <property name="name">
            <value>failure</value>
        </property>
        <property name="value">
            <value>true</value>
        </property>
    </bean>
<!-- JSON configuration end -->


    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="localeChangeInterceptor" />
            </list>
        </property>

        <property name="order" value="1" />
    </bean>
    <bean id="urlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/**/*.htm">viewController</prop>
            </props>
        </property>
    </bean>
    <bean id="viewController"
        class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />

 </beans>

测试service.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
   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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
         default-autowire="byName">

          <context:component-scan base-package="com.x.y.service">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Service"/>
    </context:component-scan>

    <import resource="test-dao.xml"/>

</beans>

测试dao.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 
xmlns:util="http://www.springframework.org/schema/util" 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/util 
http://www.springframework.org/schema/util/spring-util-3.0.xsd" default-autowire="byName">

    <context:component-scan base-package="com.x.y.dao">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    </context:component-scan>

<bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">



            <value>classpath:/database.properties</value>


        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">

        <property name="driverClassName">
            <value>${postgres.connection.driver_class}</value>
        </property>
        <property name="url">
            <value>${postgres.connection.url}</value>
        </property>
        <property name="username">
            <value>${postgres.connection.username}</value>
        </property>
        <property name="password">
            <value>${postgres.connection.password}</value>
        </property>
        <property name="maxActive">
            <value>-1</value>
        </property>
        <property name="maxIdle">
            <value>-1</value>
        </property>
        <property name="initialSize">
            <value>10</value>
        </property> 


    </bean>
    <bean id="jdbcTemplate"
        class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>



    </beans>

我面临的错误:

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 'regionService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.x.y.dao.RegionDao com.x.y.service.RegionServiceImpl.regionDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.x.y.dao.RegionDao] 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:285)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4135)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4630)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:568)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:637)
    at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:563)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:498)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1282)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:321)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:807)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445)
    at org.apache.catalina.core.StandardService.start(StandardService.java:519)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.x.y.dao.RegionDao com.x.y.service.RegionServiceImpl.regionDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.x.y.dao.RegionDao] 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:502)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
    ... 37 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.x.y.dao.RegionDao] 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:920)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
    ... 39 more

请帮助我。帮助我们。

1 个答案:

答案 0 :(得分:4)

RegionDaoImpl应该实施RegionDao。错误消息的关键位是

No matching bean of type [com.x.y.dao.RegionDao] found