问题
I have a multi-module Maven project with the following structure:
project
|
-- data
|
-- DepartmentRepository.java
|
-- domain
|
-- Department.java
|
-- service
|
-- DepartmentService.java
|
-- DepartmentServiceImpl.java
|
-- web
|
-- DepartmentController.java
The project uses Spring 4.1.4, Spring Data JPA 1.7.2 and Maven 3.1.0. The following classes are included:
@Entity class Department {}
interface DepartmentRepository extends JpaRepository<Department, Long> {}
interface DepartmentService {
List<Department> getAll();
}
@Service
@Transactional(readOnly = true)
class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentRepository departmentRepository;
@Transactional
public List<Department> getAll() {
return departmentRepository.findAll();
}
}
I was hoping that as soon as the code enters DepartmentServiceImpl.getAll
, a transaction would have been started. However, I am finding that this is not the case. No transaction is started. I have checked this by examining TransactionSynchronizationManager.isActualTransactionActive()
inside this method, which prints false
. I have also checked by putting break points in TransactionAspectSupport.invokeWithinTransaction
. However, as soon as departmentRepository.findAll
is invoked, a transaction is correctly started (since SimpleJpaRepository
, the class which provides an implementation of the JPA repository interface is also annotated with @Transactional
).
A complete sample application demonstrating the problem is available on Github.
回答1:
I noticed your annotation-driven
mode is set to aspectj
<transaction:annotation-driven mode="aspectj"/>
but you don't seem to have load-time-weaver defined anywhere in your context.
That may or may not be the issue as I only took a quick look. Also, I don't see why you would need aspectj
vs the default proxy
mode with what you have, so you might be fine just removing the mode="aspectj"
altogether and default to proxy.
来源:https://stackoverflow.com/questions/28696152/spring-transactional-not-starting-a-transaction