Spring and @transactional, is this normal?

I wrote this simple example:

//file TestController.java public interface TestController { public List<Test> findAll(); } //file TestControllerImp.java @Controller public class TestControllerImp implements TestController{ @Autowired private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory=sessionFactory; } public List<Test> findAll() { return sessionFactory.getCurrentSession().createQuery("from Test").list(); } } //file TestService.java @Service public class TestService { @Autowired private TestController controller; public boolean flag=true; public void setController(TestController controller){ this.controller=controller; } @Transactional public List<Test> useController(){ flag=false; return controller.findAll(); } } 

And this is my attempt:

 TestService s1=context.getBean(TestService.class); TestService s2=context.getBean(TestService.class); List<Test> list=s1.useController(); System.out.println(s1.flag+" "+s2.flag); 

Now weird behavior (im very new with spring):

  • If I declare the @Transactional method "useController ()", the output is: true true
  • If I move @Transactional from TestService to TestControllerImp , and I declare "findAll ()" with @Transactional , the output is false false.

Why do I have this behavior? I know that by default @Autowired classes are single, but why in the first case the flag still remains true?

Thanks to everyone.

+1
source share
1 answer

The @Transactional mechanism works on JDK proxies by default and only on interfaces.

So, if you allow TestService be an interface and TestServiceImpl be its implementation, then the above code should work.

eg. change the class declaration to this:

 @Service public class TestServiceImpl implements TestService { 

but the test code should reference the interface, not the class:

 // this code remains unchanged TestService s1=context.getBean(TestService.class); TestService s2=context.getBean(TestService.class); 

Link:

+5
source

Source: https://habr.com/ru/post/915419/


All Articles