views:

31

answers:

1

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

+1  A: 

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.

skaffman
I also thought about having such a class (I have more than one DAO, so it definitely better than have this injectSqlMapClient in every DAO), but it looks ugly for me because I need to introduce new class which I really don't need - I remove one thing (bean definitions) but get another instead (new class). But anyway, thanks for your thoughts
Jozic