簡體   English   中英

@Scheduled + Hibernate -> LazyInitializationException

[英]@Scheduled + Hibernate -> LazyInitializationException

我在 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();
    }
}

配置在這里(我省略了其他配置文件):

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

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

任何的想法?

由於使用的configureTasks這就是所謂在配置時, Syncronizer的建立是非常早。 太早了,它不再有資格進行代理創建/后處理。 這反過來又導致,至少是任務,使用未經代理的實例,而不是應用@Transactional

相反,您應該將@Scheduled注釋與cronString屬性一起使用,以與現在相同的方式解決它。

@Scheduled(cron="@appConfigProperties.cronExpression")

SpEL 表達式中的@符號表示應該解析具有給定名稱的 bean。

@Scheduled(cron = "0 30 17 * * ?")

否則我們也可以這樣使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM