Kha*_*kri 5 spring hibernate lazy-loading scheduler lazy-initialization
我在 Spring Boot 2.0.5 下,使用 Spring Data JPA
我有一堂这样的课程(为了理解):
@Component
public class Synchronizer {
@Autowired
private MyService myService;
@Transactional
public void synchronizeAuto() {
List<MyTest> tests = myService.getTests();
tests.get(0).getMyLazyObject().getName();
}
}
Run Code Online (Sandbox Code Playgroud)
配置在这里(还有其他配置文件我省略了):
@Configuration
@EnableAsync
@EnableScheduling
@EnableTransactionManagement
public class SpringAsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer {
@Autowired
private AppConfigProperties appConfigProperties;
@Autowired
private Synchronizer synchronizer;
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(appConfigProperties.getThreadpoolCorePoolSize());
executor.setMaxPoolSize(appConfigProperties.getThreadpoolMaxPoolSize());
executor.setQueueCapacity(appConfigProperties.getThreadpoolQueueCapacity());
executor.setThreadNamePrefix("threadPoolExecutor-");
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncExceptionHandler();
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addCronTask(new Runnable() {
@Override
@Transactional
public void run() {
synchronizer.synchronizeAuto();
}
}, appConfigProperties.getCronExpression());
}
}
Run Code Online (Sandbox Code Playgroud)
MyService 类调用 Spring JPA 存储库来获取所有“测试”实例
“测试”实例具有延迟加载 (MyLazyObject)
不管怎样,如果我从控制器调用该方法,一切都会变得很顺利。
当它从调度程序运行时,我收到以下错误:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.tinea.apix.service.model.entity.apim.APIManagerEntity.synchroHistory, could not initialize proxy - no Session
Run Code Online (Sandbox Code Playgroud)
任何想法?
由于使用了configureTasks在配置时调用的,所以Syncronizer很早就创建了。太早了,它不再有资格进行代理创建/后期处理。这反过来又导致,至少是任务,使用未经代理的实例并且没有@Transactional申请。
相反,您应该使用@Scheduled注释和cronString属性来解决它,就像现在一样。
@Scheduled(cron="@appConfigProperties.cronExpression")
Run Code Online (Sandbox Code Playgroud)
SpEL 表达式中的符号@指示应解析具有给定名称的 bean。
| 归档时间: |
|
| 查看次数: |
3162 次 |
| 最近记录: |