Provide third party objects via PicoContainer

75 views Asked by At

Using MyBatis, I find myself having many mapper interfaces, e.g.

public interface BlogMapper {
  @Select("SELECT * FROM blog WHERE id = #{id}")
  Blog selectBlog(int id);
}

Which are retrieved on demand using a MyBatis factory

final BlogMapper mapper = session.getMapper(BlogMapper.class);

Now, I'd like to allow constructor injection of those interfaces (implemented under the hood by MyBatis), so I cannot explicitly

container.addComponent(...);

What's the best way to accomplish this?
I suppose some kind of ComponentAdapter or ComponentMonitor would be the right pick.

1

There are 1 answers

4
xeye On

You need a kind of custom factory for mybatis mapper instances and pico has ComponentAdapters API for this purpose. Check http://picocontainer.com/adapters.html and also the standard implementations if something is unclear. You will need to create Adapter instance per mapper, calling session.getMapper(Type) inside its getComponentInstance, thus encapsulating the special case for mapper instances creation. This adapter instance should be added with container.addAdapter() method. If you don't want to do this manually each time, you need to leverage ComponentFactory, that will produce those ComponentAdapters.

Another way is to create higher level DAOs/Repos (one for each mapper), they will have mybatis SessionFactory injected, have a method for getting specific mapper and then delegate calls to the mapper with proper business grouping/validation/tx wrapping etc. Those higher level DAOs are added to the container to be injected into other components.

BTW. http://picocontainer.com/ has lot of interesting info hidden behind "View/Hide Sitemap Inline ..." link on the page top. Don't ask why :)