6

我想使用@Repository spring 注释来避免在 context.xml 中添加 bean。我使用 ibatis 集成,所以我的存储库类看起来像这样

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

SqlMapClientDaoSupport(spring 库类)具有设置未使用 @Autowired 或 @Resource 注释的所需属性的最终方法

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

SqlMapClient bean 在 spring context.xml 中定义。如果在 XML 中定义了 userDao bean,它可以正常工作,但是当我放置 @Repository 注释并删除 bean 声明时,我得到以下异常

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

一种解决方法可以是添加新方法,例如

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

但它看起来很丑

有没有其他方法可以在没有定义的情况下注入属性?

4

1 回答 1

3

引入一个中间超类怎么样?

public class AutowiringSqlMapClientDaoSupport extends SqlMapClientDaoSupport {

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

进而

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

于 2010-09-27T20:58:33.280 回答