Update: This is a poor solution as it makes the service depend on the client. See below for updated solution.
Simply with a @PostConstruct
so that the Service has the ServletContext set before it isRunning.
@Controller
@RequestMapping("/manifests")
public class ManifestEndpoint {
@Autowired
private ManifestService manifestService;
@Autowired
ServletContext servletContext;
@PostConstruct
public void initService() {
manifestService.setServletContext(servletContext);
}
Then in the service be sure to check it is used, since that can't be guaranteed.
@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();
}
Updated solution that doesn't make the service depend on the client.
@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);
}
The ManifestService doesn't change (that is, there is no need for buildManifestCurrentWebApp() now).