Spring-如何将ServletContext转换为@Service(+如何获取WebApps清单) [英] Spring - how to get ServletContext into a @Service (+ how to get WebApps Manifest)
问题描述
在Web应用程序的@Controllers
中,您可以自动连接Servlet上下文,以便(就我而言)可以从Web应用程序获取清单(请参见https://stackoverflow.com/a/615545/1019307 ).
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;
您如何将其纳入服务?
我实现了这种简单的模式,并认为自己会分享.
I implemented this simple pattern and thought I'd share.
推荐答案
更新:这是一个较差的解决方案,因为它使服务依赖于客户端.有关更新的解决方案,请参见下文.
只需使用@PostConstruct
,以便Service在运行之前设置ServletContext.
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();
}
未使服务依赖于客户端的更新解决方案.
@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);
}
ManifestService不变(也就是说,现在不需要buildManifestCurrentWebApp()).
The ManifestService doesn't change (that is, there is no need for buildManifestCurrentWebApp() now).
这篇关于Spring-如何将ServletContext转换为@Service(+如何获取WebApps清单)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!