在超类中为@Repository bean注入派生属性,而无需@Autowired [英] injecting derived property for @Repository bean without @Autowired in super class

查看:292
本文介绍了在超类中为@Repository bean注入派生属性,而无需@Autowired的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用@Repository spring注释来避免在context.xml中添加bean. 我使用ibatis集成,因此我的存储库类如下所示:

I would like to use @Repository spring annotation to avoid adding bean in context.xml. I use ibatis integration, so my repository class looks like this

@Repository("userDao")
public class UserDaoMybatis extends SqlMapClientDaoSupport implements UserDao {
    // ...
}

SqlMapClientDaoSupport(spring库类)具有用于设置必需属性的最终方法,该属性未使用@Autowired或@Resourse注释

SqlMapClientDaoSupport (spring library class) has final method for setting required property which is not annotated with @Autowired or @Resourse

public final void setSqlMapClient(SqlMapClient sqlMapClient) {
    if (!this.externalTemplate) {
        this.sqlMapClientTemplate.setSqlMapClient(sqlMapClient);
    }
}

SqlMapClient bean是在spring context.xml中定义的. 如果userDao bean是用XML定义的,则可以正常工作,但是当我放置@Repository批注并删除bean声明时,会出现以下异常

SqlMapClient bean is defined in spring context.xml. If userDao bean is defined in XML it works fine, but when I put @Repository annotation and remove bean declaration I get the following exception

java.lang.IllegalArgumentException: Property 'sqlMapClient' is required

一种解决方法是添加

@Aitowired
injectSqlMapClient(SqlMapClient sqlMapClient) {
    setSqlMapClient(sqlMapClient);
}

但是看起来很丑

您是否还有其他方法可以在未定义的情况下注入该属性?

Is there any other way yo inject the property without having defined?

推荐答案

如何引入中介超类?

public class AutowiringSqlMapClientDaoSupport extends SqlMapClientDaoSupport {

   @Autowired
   injectSqlMapClient(SqlMapClient sqlMapClient) {
      setSqlMapClient(sqlMapClient);
   }
}

然后

@Repository("userDao")
public class UserDaoMybatis extends AutoringSqlMapClientDaoSupport implements UserDao {
    // ...
}

是的,这是对继承的滥用,但不比现有的SqlMapClientDaoSupport更糟,如果您迫切希望避免DAO类本身中的注入钩子,那么我想不出更好的方法.

Yes, it's abuse of inheritance, but no worse than the existing SqlMapClientDaoSupport, and if you're desperate to avoid the injection hook in the DAO class itself, I can't think of a better way.

这篇关于在超类中为@Repository bean注入派生属性,而无需@Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆