Spring - how to get ServletContext into a @Service (+ how to get WebApps Manifest)

孤街醉人 提交于 2019-12-08 10:03:05

问题


In a Web App's @Controllers you can autowire your Servlet Context so you can (in my case) get the Manifest from the web-app (see https://stackoverflow.com/a/615545/1019307).

@Autowired
ServletContext servletContext;

How do you get this into the service?

I implemented this simple pattern and thought I'd share.


回答1:


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).



来源:https://stackoverflow.com/questions/37475810/spring-how-to-get-servletcontext-into-a-service-how-to-get-webapps-manifes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!