我有一个Controller,它调用一个具有@Transactional注释的Service。
但是,当我声明bean MethodValidationPostProcessor时,no事务被创建了(无法初始化代理-没有会话)。
@EnableWebMvc
@ComponentScan(basePackages = {"my"})
public class Application extends WebMvcConfigurerAdapter {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}控制器bean:
@RestController
@RequestMapping(path = "/my", produces = APPLICATION_JSON_VALUE)
public class MyController {
@Autowired
private TransactionalService transactionalService;
@RequestMapping(method = POST)
public void post(@SafeHtml @RequestBody String hey) {
transactionalService.doStuff(hey);
}
}服务bean:
@Service
public class TransactionalService {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void doStuff(String hey) {
Item h = entityManager.find(Item.class, hey);
h.getParent(); // could not initialize proxy - no Session
}
}当我声明@Transactional时,我想了解为什么MethodValidationPostProcessor不能工作。谢谢!
注意:如果我在我的Controller上添加了“事务处理”,它就能工作。但这不是我想做的。
发布于 2016-09-19 15:57:50
多亏了@Kakawait,我找到了一个解决方案:声明我的bean MethodValidationPostProcessor。需要是static,这样@Transactional仍能正常工作。
/**
* This bean must be static, to be instantiated before the other MethodValidationPostProcessors.
* Otherwise, some are not instantiated.
*/
@Bean
public static MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}https://stackoverflow.com/questions/39533215
复制相似问题