MethodValidationPostProcessor打破@Transactional

时间:2016-09-16 13:51:41

标签: spring transactions bean-validation

我有一个Controller,可以调用Service @Transactional注释。

但是当我声明bean MethodValidationPostProcessor时,没有创建任何事务(无法初始化代理 - 没有会话)。

@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时无效的原因。谢谢!

注意:如果我在我的控制器上添加@Transactional,它可以正常工作。但这不是我想做的事。

1 个答案:

答案 0 :(得分:2)

感谢@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();
}