I want to get the ServletContext in a Java Spring Webproject and use
it to get the absolute path of my web-application project. I'm still a
beginner in JavaEE and Spring, so maybe I've got some concepts wrong.
In the java class, in which I want to use the ServletContext, I got
only an empty object when using @Autowired ServletContext context;
But in my RestConfiguartion class, which extends the
WebMvcConfigurerAdapter class, I got the ServletContext and I'm able
to use it in a Java Bean, with the return type of ServletContext. But I
have no idea, how I can use the Bean in another class to get the
ServletContext, is this possible?
@Configuration
@EnableWebMvc
@Import({ ServiceConfiguration.class, SecurityConfiguration.class })
@ComponentScan(basePackages = { "de.rest", "de.security" })
public class RestConfiguration extends WebMvcConfigurerAdapter {
@Autowired
ServletContext context;
@Bean
public ServletContext getServletContext() {
System.out.println("*** Context path: *** " + context.getRealPath("/"));
return context;
}}
你可以写
@Autowired
ServletContext context;
在其他 bean 注释类中也是如此。您将获得相同的上下文。
因此,您不需要指定:
@Bean
public ServletContext getServletContext() {
System.out.println("*** Context path: *** " + context.getRealPath("/"));
return context;
}}
例如(注释中指定的目录中的任何类@ComponentScan
):
@Bean
class X {
@Autowired
ServletContext context;
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)