1

beans:profiles在我的xml中使用过这样的:

    <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>

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

<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:无法自动装配字段:私有 MyService MyController.myService;嵌套异常是 org.springframework.beans.factory.BeanCreationException:

嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为“dbService”的 bean 时出错:注入自动装配的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配方法:public void DBServiceImpl.setDataSource(javax.sql.DataSource); 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型为 [javax.sql.DataSource] 的匹配 bean:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注释:org.springframework.beans.factory.support 的 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287) 中的 {}。

4

1 回答 1

1

My guess it that you are using profile in DispatcherServlet context, while DataSource is likely located in the root application context.

See Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

update: try using context-params (taken from here):

<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
于 2012-11-09T16:18:00.220 回答