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.
source share