开发者

injecting derived property for @Repository bean without @Autowired in super class

开发者 https://www.devze.com 2023-01-18 06:57 出处:网络
I would like to use @Repository spr开发者_开发百科ing annotation to avoid adding bean in context.xml.

I would like to use @Repository spr开发者_开发百科ing 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 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 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

A workaround can be to add new method like

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

but it looks ugly

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


How about introducing an intermediary superclass?

public class AutowiringSqlMapClientDaoSupport extends SqlMapClientDaoSupport {

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

and then

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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消