使用bean后未加载@Autowired bean:3.1版本中的配置文件

时间:2012-11-09 16:05:04

标签: spring spring-mvc spring-3 autowired

我在我的xml中使用了beans:profiles,如下所示:

    <beans profile="dev">
        <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}" />
            <property name="url" value="${jdbc.internal.url}" />
            <property name="username" value="${jdbc.internal.username}" />
        </bean>
   </beans>

我在web.xml中设置了spring.active.profiles

<servlet>
    <servlet-name>myapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/myapp-servlet.xml</param-value>
    </init-param>
    <init-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>dev</param-value>
    </init-param>
</servlet>

我的代码结构是这样的:

//controller
@Controller 
public class MyController {
  @Autowired
  private MyService myService;
  ....
}

//service implementation
@Service("myservice")
public class MyServiceImpl implements MyService {
  @Autowired
  DBService dbService;
} 

//db service
@Service("dbservice)
public class DBServiceImpl implements DbService {
  @Autowired
  public void setDataSource (Datasource ds) { 
    this.jdbcTemplate = new JdbcTemplate(ds);
  }
}

错误:

  

创建名为'myController'的bean时出错:注入   自动连接依赖失败;嵌套异常是   org.springframework.beans.factory.BeanCreationException:不能   autowire字段:私有MyService   MyController.myService;   嵌套异常是   org.springframework.beans.factory.BeanCreationException:

     

嵌套异常是   org.springframework.beans.factory.BeanCreationException:错误   创建名为'dbService'的bean:注入自动装配   依赖失败;嵌套异常是   org.springframework.beans.factory.BeanCreationException:不能   autowire方法:public void   DBServiceImpl.setDataSource(javax.sql.DataSource中);嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   为依赖项找到匹配的类型为[javax.sql.DataSource]的bean:   预计至少有1个豆有资格成为autowire候选人   这种依赖。依赖注释:{} at   org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)     在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)     在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)

1 个答案:

答案 0 :(得分:1)

我猜你在DispatcherServlet上下文中使用了profile,而DataSource可能位于根应用程序上下文中。

请参阅Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

更新:尝试使用context-params(取自here):

<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>