簡體   English   中英

如何在OSGI環境中避免MyBatis的類加載問題?

[英]How to avoid classloading issues with MyBatis in OSGI environment?

我正在使用具有多個模塊的基於Eclipse 3.7 RCP的應用程序。 模塊A是一堆庫,包括mybatis-3.2.2.jar。 模塊B依賴於模塊A(manifest.mf中的Require-Bundle),並且具有使用MyBatis訪問數據庫中數據的代碼。 我已經在模塊B中導出了包含映射器類和XML的包,並將它們導入到模塊A中。我在代碼中構建了SqlSessionFactory,如果我按名稱添加所有Mapper類,它可以正常工作,例如

configuration.addMapper(MyMapper.class);

但是當我嘗試在包中添加所有Mappers時:

configuration.addMappers(MyMapper.class.getPackage().getName());

MyBatis沒有看到它們。

我嘗試更改默認的類加載器,但這沒有幫助。

Resources.setDefaultClassLoader(this.getClass().getClassLoader());

我懷疑這個問題與OSGI環境中類的可見性有關。 如果是這種情況,有沒有辦法在應用程序中修復它?

你有沒有嘗試過

Resources.setDefaultClassLoader(Activator.class.getClassLoader()) 我認為這將使用OSGi類加載器。 希望這會有所幫助。

我在Felix OSGi環境中遇到了與Spring Data JPA類似的問題。 在這種情況下,我能夠覆蓋工廠類並將其添加到違規方法中:

ClassLoader pre = Thread.currentThread().getContextClassLoader();
try {
    Thread.currentThread().setContextClassLoader(context.getClassLoader());
    // add mappers here or call super method
} finally {
    Thread.currentThread().setContextClassLoader(pre);
}

在這種情況下,“context”是Spring上下文,但您應該能夠從BundleWiring獲取Module B的類加載器。

Bundle bundle; //get this by symbolic name if you don't have a reference
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
bundleWiring.getClassLoader();

希望addMappers方法不需要在同一個調用中訪問Module A的類加載器。 如果是這種情況,除非有擴展和注入不同Configuration或MapperRegistry類的方法,否則你將無法做到這一點。

暫無
暫無

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

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