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;
...
}
关于java - Spring 获取 ServletContext 并将其作为 Bean 提供,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47269496/