2017-02-21 23 views
0

我有一個處女座Tomcat服務器正在運行。有一個EnumMap的,從這個圖OSGi:如何獲得其他包的類加載器

bundle.a.MyEnum 

上下文通過使用SpelExpressionParser

bundle.b 

和Spring表達式語言獲得其關鍵是,一個樣品的表達是「得到(T(bundle.a .MyEnum).SAMPLEKEY)」。 Parser(分別是它的TypeLocator)需要訪問bundle.a的ClassLoader。

所以我做:

TypeLocator typeLocator = new StandardTypeLocator(getBundleAClassLoader()); 
StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); 
evaluationContext.setTypeLocator(typeLocator); 
spelExpressionParser = new SpelExpressionParser(); 
spelExpressionParser.parseExpression(expression)).getValue(evaluationContext, context); 

的問題是,什麼是正確的方式來獲得bundle.a的類加載器的類bundle.b的? 一對夫婦嘗試後,唯一的工作解決我發現是:

private static ClassLoader getBundleAClassLoader() { 
    MyEnum bundleARef = MyEnum.SAMPLEKEY; 
    return bundleARef.getClass().getClassLoader(); 
} 

編輯:解

getBundleAClassLoader() 

是沒有必要的,

TypeLocator typeLocator = new StandardTypeLocator(this.getClass().getClassLoader()); 

工作正常。

回答

1

這聽起來太複雜了。只需在bundle.b的Manifest中執行一個Import-Package,並且可以像您自己的類型一樣訪問該類型。

+0

bundle.b進口bundle.a,但沒有StandardEvaluationContext,春節級SpelParserExpression將使用bundle.b的導致一個ClassNotFoundException – pma

+0

的類加載器。如果bundle.b進口MyEnum然後Bundle.b的類加載程序包將找到類bundkle.a.MyEnum –

+0

我站在糾正,它的工作原理。猜測當我嘗試this.getClass()。getClassLoader()時,我沒有正確設置TypeLocator。謝謝! – pma

1

例如

SomeClassOfBundle.class.getClassLoader() 

bundle.adapt(BundleWiring.class).getClassLoader() 
+0

我嘗試了第一個建議,但沒有奏效。我也嘗試了第二種方法,使用Bundle b = bundleContext.getBundle(),這會導致bundle.b,從而導致它的ClassLoader。也許我應該使用getBundles()來代替正確的。 – pma

+0

你的意思是「沒有工作」是什麼意思?捆綁線路錯誤?如果您想使用第一種方法,則需要在Manifest文件中爲SomeClassOfBundle包提供一個Import-Package。 – Puce

+0

我很積極我有昨天測試的第一種方法,並收到一個ClassNotFoundException。但是,我再次測試它,它工作。由於基督徒的回答引導我this.getClass()。getClassLoader()我接受了他的答案,但謝謝你。 – pma