java - Spring 获取 ServletContext 并将其作为 Bean 提供

标签 java spring spring-mvc servlets javabeans

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/

相关文章:

java - Spring Security BadCredentialsException 异常

java - mvc :resources - Spring 的注解配置替换

java - 为什么我的方面不起作用?

java - 类可以作为方法的参数吗?

java - 如何在 Spring 和 JPA/Hibernate 中实现工作单元?

java - Spring中使用表达式语言出错

java - 无法打开 Hibernate session 进行事务;嵌套异常是 org.hibernate.exception.GenericJDBCException : Could not open connection

java - Spring MVC、Spring Security、数据库控制的页面访问

java - 如何将这两者分开?我的意思是2个不同的帐户

java - 从 Spring Boot 1.5 迁移到 2,多个数据源上出现错误