Rick wrote:
> I'm starting simple to get the hang of this, so I'd appreciate any
> recommendations on how to set this up better and what I'm doing wrong.
>
> I have a TestModule that binds a provider:
>
> protected void configure() {
>
> bind(SqlSessionFactory.class).toProvider(SqlSessionFactoryProvider.class);
> bind(EmployeeDao.class).to(EmployeeDaoIbatis.class);
> bind(EmployeeService.class).to(EmployeeServiceImpl.class);
> }
>
>
> The Provider class above, I only want instantiated ONCE, whether in the
> application or during tests. It has to read in resource files etc and is
> somewhat expensive to run.
>
> I'm using MyCila 2.1 plugin with JUnit4 and have it set up like:
>
> @GuiceContext(TestModule.class)
> public abstract class BaseTest extends MycilaJunit4Test {
>
> @Test
> public void doNothing() {
> //just to avoid warnings
> }
> }
>
> I don't mind that the TestModule ends up instantiated on every Test
> class run (although does it have to?),
I'm not aware of a way to share resources between multiple JUnit Test
classes. You'd best seek advice from JUnit experts.
> but how do I set it up so that my
> Provider isn't run repeatedly during the tests?
Bind the provider in singleton scope. Either by annotating your provider
class @Singleton or calling bind(MyProvider.class).in(Singleton.class);
> As a side note, is the below the kind of thing that should be done in a
> provider (seems cleaner here than in some static block)? (Defining as a
> Singleton since only want one instance.)
>
> @Singleton
Huh, you already had it annotated? Weird, this annotation on the
provider definitely causes Guice 2.0 to only instantiate the provider
once in a simple test I tried.
> public class SqlSessionFactoryProvider implements
> Provider<SqlSessionFactory> {
> private static final Log log =
> LogFactory.getLog(SqlSessionFactoryProvider.class);
> private static final String resource = "ibatis-config.xml";
>
> private SqlSessionFactory sqlSessionFactory;
>
> public SqlSessionFactoryProvider() {
> System.out.println("!!!!!! Creating SqlSessionFactory from
> resource");
> Reader reader;
> try {
> reader = Resources.getResourceAsReader(resource);
> Properties props =
> Resources.getResourceAsProperties("application.properties");
> String environment = props.getProperty("environment");
> sqlSessionFactory = new
> SqlSessionFactoryBuilder().build(reader, environment);
>
> //run some db scripts
> GroovySqlPersistence.initialize();
>
> } catch (IOException ex) {
> throw new RuntimeException("Could not find the resource:
> "+resource, ex);
> }
>
> }
>
> public SqlSessionFactory get() {
> return sqlSessionFactory;
> }
> }
Well, a big part of DI is to help you avoid static singletons. I agree
it helps you little with the code as it is, but what if you wanted to
inject configuration into the SqlSessionFactoryProvider instead of
hardcoding it? Then it becomes inappropriate for it to be a static
singleton.
Max.
signature.asc
Description: OpenPGP digital signature
