Results 1 to 3 of 3

Thread: @Autowired prevent LazyInitializationException why ?

  1. #1
    Join Date
    Jun 2011
    Posts
    2

    Default @Autowired prevent LazyInitializationException why ?

    I have a simple junit test class that use a simple bean service retrieved whether with @Autowired annotation or ctx.getBean() call.

    In the second case I'm facing a LazyInitializationException when I try to read data from a lazy loaded collection. I assume this is because the session has been closed in the DAO service.

    My question is, why I don't have this kind of trouble with the @Autowired way ?

    Code:
    @ContextConfiguration(locations = { "classpath*:spring/applicationContext.xml" })
    @RunWith(SpringJUnit4ClassRunner.class)
    @Transactional
    public class SimpleTest {
    
    @Autowired
    private IService service;//first scenario ok
    
    private IService service = ...getBean("myService");// second scenario ko
    
    @Test
    public void myTest() {
      MyObject myOo = service.retrieveMyObject("ref#1");
      List list = myOo.getLazyCollectionOfSomething(); // ok with @Autowired service but LazyInitializationException with ...getBean() 
      ...
    }
    
    }
    Any idea ?
    I would be happy if I could understand :-)
    Please feel free to answer me
    Best Regards

  2. #2

    Default

    Using Spring class runner will automatically register "TransactionalTestExecutionListener" which enables the transactional support for your tests.

    Are you autowiring the ApplicationContext or creating it manually via "new"? If you are bypassing Spring's test support (not using Spring's class runner) you do not have transactional support on your test. Spring will manage transactions declared in your ApplicationContext or annotated beans (e.g.dao, service) but your test is not transactional in that case.


    nicolas.loriente

  3. #3
    Join Date
    Jun 2011
    Posts
    2

    Default

    Hi Nicolas,
    That sounds clear, thank you for answering.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •