2016-05-27 15 views
0

Webアプリケーションのでは、サーブレットコンテキストをオートワイヤリングして、Webアプリケーションからマニフェストを取得することができます( https://stackoverflow.com/a/615545/1019307)。Spring - ServletContextを@Serviceに取得する方法(+ WebAppsマニフェストを取得する方法)

@Autowired 
ServletContext servletContext; 

これをサービスにどのように取得しますか?

私はこの単純なパターンを実装し、分かち合うと思っていました。

+2

あなたはしないでください。あなたのサービス層は、あなたが効果的にやっているように、Web層に依存すべきではありません。あなたが避けるべきもの。 –

+0

+1 @ M.Deinum ... @HankCa、あなたのコントローラーに 'buildManifest'の2行を入れてください...どんなサービス層でもサーブレットコンテキストを渡さないでください... – Pras

+0

はい、あなたは正しいです私。提案通りに更新されました。 – HankCa

答えて

0

更新:サービスをクライアントに依存させるため、これは貧弱なソリューションです。更新されたソリューションについては以下を参照してください。

@PostConstructとするだけで、サービスはisRunningの前にServletContextを設定します。

@Controller 
@RequestMapping("/manifests") 
public class ManifestEndpoint { 
    @Autowired 
    private ManifestService manifestService; 

    @Autowired 
    ServletContext servletContext; 

    @PostConstruct 
    public void initService() { 
     manifestService.setServletContext(servletContext); 
    } 

サービスでは、保証されていないため、必ず使用していることを確認してください。

@Component 
public class ManifestService { 
    .... 
    public void setServletContext(ServletContext servletContext) { 
     this.servletContext = servletContext; 
    } 

    private void buildManifestCurrentWebApp() { 
     if (servletContext == null) { 
      throw new RuntimeException("ServletContext not set"); 
     } 
     # Here's how to complete my example on how to get WebApp Manifest 
     try { 
      URL thisAppsManifestURL = servletContext.getResource("/META-INF/MANIFEST.MF"); 
      System.out.println("buildManifestCurrentWebApp - url: "+thisAppsManifestURL); 
      buildManifest(thisAppsManifestURL); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } 

サービスは、クライアントに依存せないソリューションを更新しました。 ManifestServiceは変更されません

@Controller 
@RequestMapping("/manifests") 
public class ManifestEndpoint { 
    private static final Logger logger = LoggerFactory.logger(ManifestEndpoint.class); 
    @Autowired 
    private ManifestService manifestService; 

    @Autowired 
    private ServletContext servletContext; 

    @PostConstruct 
    public void initService() { 
     // We need to use the Manifest from this web app. 
     URL thisAppsManifestURL; 
     try { 
      thisAppsManifestURL = servletContext.getResource("/META-INF/MANIFEST.MF"); 
     } catch (MalformedURLException e) { 
      throw new GeodesyRuntimeException("Error retrieving META-INF/MANIFEST.MF resource from webapp", e); 
     } 
     manifestService.buildManifest(thisAppsManifestURL); 
    } 

は(つまり、何buildManifestCurrentWebAppの必要性()今はありません)。

関連する問題