Spring 3 个带有休眠 CRUD 操作的注释:@Autowired 未按预期工作

Spring 3 Annotations with hibernate CRUD operations : @Autowired not working as expected

我目前正在使用 Spring 3 注释和 hibernate 3 进行数据库连接。我还必须使用 spring 个图块。
我的 spring-servlet.xml 是:

    <context:annotation-config />
<context:component-scan base-package="com.xxx.controller,com.xxx.dao,com.xxx.service" />

<mvc:annotation-driven />

<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"
    id="viewResolver">
    <property name="viewClass">
        <value>
            org.springframework.web.servlet.view.tiles2.TilesView
        </value>
    </property>
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"
    id="tilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/plugin/impl/tiles/springtiles-defs.xml</value>
        </list>
    </property>
</bean>

//Is this required????
<!-- <bean id="MyDAO" class="com.xxxx.MyDAOImpl"></bean>
<bean id="MyService" class="com.xxxx.MyServiceImpl"></bean> -->

我的控制器class:

@Controller
public class myController {

    @Autowired
    private MyService myService;
    public myController() {

    }

    @RequestMapping(value="/index.do", method = RequestMethod.GET)
    protected ModelAndView Submit(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // TODO Auto-generated method stubs
        System.out.println(" Inside the controller ");

</beans>

还有我的 serviceImpl class:

    @Service("MyService")
public class MyServiceImpl implements MyService{

@Autowired
MyDAO myDAO;

还有我的 DaoImpl class :

   @Repository/*("myDAO")*/
   public class MyDAOImpl implements MyDAO{

List<String> clientList;

 @Autowired
 private SessionFactory sessionFactory;

 private Session session;

 private Session currentSession() {
        return this.sessionFactory.getCurrentSession();
    }

@Override
public List<ClientInfoBean> getClientList(String currentQrt) throws DataStoreException {
    // TODO Auto-generated method stub
    return (List<ClientInfoBean>) this.currentSession().
    createCriteria("Select * from myTable);
}

它仍然给出以下例外情况。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxx.service.MyService com.xxx.controller.MyController.MyService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService] 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:288) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116) 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.getObject(AbstractBeanFactory.java:295)

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxx.service.MyService com.xxx.controller.MyController.MyService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService] 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:514) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) ... 97 more

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxx.service.MyService] 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:486) ... 99 more

异常明明告诉你bean没有配置 NoSuchBeanDefinitionException:没有 [com.xxx.service.MyService]

类型的合格 bean

你能检查一下你在注解中给出的 bean 名称是否与参数名称匹配吗?我的服务与我的服务。

另外添加一个 setter 可能是个好主意,因为 spring 可以调用 setter 来注入依赖项而不是使用反射来注入它。

当您将服务限定为 "MyService" 时,您可以添加如下限定符以找到它。默认情况下 spring 应该按类型自动装配,所以组件扫描应该加载你的服务。如果您在 xml 中部分定义 beans 并希望自动装配其他服务,则必须添加 spring-servlet.xml

@Autowired
  @Qualifier("MyService")
    private MyService myService;

同时将您的控制器 class 更改为 MyController 而不是 myController。 并且 删除构造函数 myController(),spring 将为您构造控制器 bean。尝试删除所有 spring bean classes 中的所有构造函数,spring 将为您构造。一开始,您可以避免对 bean 进行限定,删除括号中的名称("MyService"、"MyDao" 等....)

当你定义 @Service("MyService") public class MyServiceImpl implements MyService{ } 要么 @Repository("MyDAO") public class MyDAOImpl implements MyDAO{ } 您实际上是在告诉 spring 创建名称为 "MyService" & "MyDAO"

的 bean

当你定义喜欢 @Autowired private MyService myService; @Autowired private MyDAO myDAO; 您要求 spring 提供名称为 "myService" & "myDAO".

的 bean

由于 spring 创建的 bean 名称与您要求的名称不同,因此会报错。 您必须将 @Service 和 @Repository 注释中的 bean 名称与接口的变量名称保持一致。

@Service("myService")
public class MyServiceImpl implements MyService{
}

private MyService myService;

使用

@Service
public class MyServiceImpl implements MyService

而不是

@Service("MyService")
public class MyServiceImpl implements MyService{

所以问题出在您的包裹上:

您在以下位置定义了服务和 daos:com.xxx.servicecom.xxx.dao

以及您在 com.xxx.serviceImplcom.xxx.daoImpl.

中的实施

也加入<context:component-scan base-package="com.xxx.serviceImpl,com.xxx.daoImpl"/>

您面临的下一个问题是事务管理:

您还没有在 spring 配置中定义它。这是一个如何执行此操作的示例:

<!-- Hibernate 3 Annotation SessionFactory Bean definition-->
<bean id="sessionFactory"
      class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.jdbc.batch_size">${batchSize}</prop>
        </props>
    </property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

在此之后,您需要将方法或服务实现标记为 @Transactional,以便 spring 处理此问题。