2011-11-08 103 views
2

我正在開發某種應由外部java應用程序調用的插件。 我的插件使用春天,因爲我試圖簡化我的,因爲我可以:如何在Spring應用程序上下文外創建Spring Bean

讓我們考慮這是3D派對應用程序,它的主要功能調用我的插件。

public class ThirdPartyClass { 

    public static void main(String[] args) { 
     GeneralPlugin plugin = new MyPlugin(); 
     plugin.init(); 
     //calling ext. plugin functionality. 
     plugin.method1(); 
    } 
} 

現在,這是我的插件

package com.vanilla.spring; 

@Component 
    public class MyPlugin implements GeneralPlugin{ 

     @Autowired 
     Dao mydao; 

     public void init(){ 
      //some initiation logic goes here... 
     } 

     public void method1(){ 
      dao.delete(); 
     } 
    } 

現在我的道

package com.vanilla.spring; 

Component(value="dao") 
public class MyDao { 

    public void delete(){ 
//SOME DATABASE LOGIC GOES HERE!!! 
} 
} 

現在我的XML:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:p="http://www.springframework.org/schema/p" 
xmlns:context="http://www.springframework.org/schema/context" 
xsi:schemaLocation=" 
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
<context:annotation-config /> 
<context:component-scan base-package="com.vanilla.spring"></context:component-scan> 
</beans> 

我的問題是,我道是空和我訪問dao時會得到NullPointerException對象。

我 米相信它是因爲我萌生出豆應用程序上下文和我的自動裝配不正常的結果。

是否有任何其他方法,使自動裝配工作?

+3

你的代碼需要初始化Spring上下文 - 除非你告訴它春天不會初始化。 –

回答

3

「春豆」 只是:的Java bean。除了通過繼承或對象實例賦予它們之外,它們沒有內在的能力。

Spring應用程序上下文負責創建bean並「連線」它,這是在上下文中創建其他bean的過程,並使用結果調用bean的setter(和構造函數)來配置它們。要做到這一點,使用XML配置文件和註釋來決定要創建什麼以及在哪裏放置它。

如果你不打算使用的實際應用上下文的,那麼你必須做所有的工作自己,手動。也就是說,用適當的數據源創建DAO,創建插件bean,並在插件bean上設置DAO。

在這個特定的例子中,由於第三方應用程序控制插件bean的實例化,您可能必須a)在插件構造函數中創建DAO(這是您在Spring中使用以避免或者b)在插件構造函數中創建一個Application Context,並通過查詢上下文來引用插件所需的bean。這不像讓上下文做所有事情一樣有用,但至少你不需要手動配置應用程序使用的其餘bean(包括用戶名,連接URL等)。

如果你去那麼你就需要在Spring配置文件中的某處類路徑或者以某種方式以其他方式能夠在第二條路線由插件豆引用。

+0

我認爲OP意味着使用上下文,只是沒有初始化它。 –

+1

他的插件正在被第三方應用程序實例化,他認爲註釋會以某種方式啓動並填充DAO。 –

+0

這就是爲什麼他需要初始化他的應用程序上下文。 –

相關問題