更新:サービスをクライアントに依存させるため、これは貧弱なソリューションです。更新されたソリューションについては以下を参照してください。
@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の必要性()今はありません)。
あなたはしないでください。あなたのサービス層は、あなたが効果的にやっているように、Web層に依存すべきではありません。あなたが避けるべきもの。 –
+1 @ M.Deinum ... @HankCa、あなたのコントローラーに 'buildManifest'の2行を入れてください...どんなサービス層でもサーブレットコンテキストを渡さないでください... – Pras
はい、あなたは正しいです私。提案通りに更新されました。 – HankCa