2013-07-25 42 views
0

我創建了一個非常出色的彈簧項目jar。我已經將這個jar導入另一個spring項目。現在,我想訪問一些在彈簧罐中製作的實例。例如,下面的類是來自內部春季項目。我想獲取AuthenticationClient的實例。我編程的方式是創建一個靜態的getter方法,它將返回實例的引用。對於要在靜態引用中設置的實例,我必須在Listener中自動裝入它。無法從其他彈簧項目導入的彈簧項目jar中訪問實例

因爲我已經將jar導入到另一個Spring項目中,我發現最終沒有調用listener,失敗了所有的事件鏈。下面是外彈簧項目中,我試圖訪問AuthenticationClient

實例豆

public class AuthenticationClient { 

private @Autowired KerberosAPI kerberosAPI; 
private @Autowired KerberosSessionManager kerberosSessionManager; 
private static AuthenticationClient client; 

public static AuthenticationClient getAuthenticationClient(){ 
    return client; 
} 

public @Resource(name="authenticationClient") void setAuthenticationClient(AuthenticationClient client){ 
    AuthenticationClient.client = client; 
} 

監聽

public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent>` { 

private @Autowired AuthenticationClient client; 

@Override 
public void onApplicationEvent(ContextRefreshedEvent event) { 
    ApplicationContext applicationContext = event.getApplicationContext(); 
    System.out.println(); 
    // now you can do applicationContext.getBean(...) 
    // ... 
} 

}的控制器

控制器

@Controller 

public class HomeController { 

private AuthenticationClient client; 

/** 
* Simply selects the home view to render by returning its name. 
*/ 
@RequestMapping(value = "/", method = RequestMethod.GET) 
public String home(Locale locale, Model model) { 
    client = AuthenticationClient.getAuthenticationClient(); 

    return "home"; 
} 

}

+0

爲什麼不直接使用@Autowired或@Resource來直接禁用AhthenticationClient? – Hippoom

+0

AuthenticationClient類具有一些其他依賴關係,而這些依賴關係又具有其他一些嵌套依賴關係。 –

+0

你想單獨使用AuthenticationClient?我的意思是沒有它的依賴? – Hippoom

回答

0

對於誰是尋找答案的一些其他用戶的參考。我們可以將jar的上下文文件導入到我們當前的項目中。確保jar在類路徑中。然後,你導入這樣的上下文

<beans:import resource="classpath:/src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml"/> 
+0

我退出了src/main/webapp是一個源文件夾,你是否在啓動web應用時測試它? – Hippoom

+0

是的,我也這麼想。以前,我從WEB-INF提供的未能加載上下文的類路徑。但一些如何給完整的路徑工作 –

+0

這是「servlet-context.xml」在你的jar或在你的項目擴展目錄下? – Hippoom

相關問題