Cang_Feng 2023-02-23 10:25 采纳率: 50%
浏览 46

Spring监听器全局初始化参数怎么使用注解核心配置类

在学习Spring mvc时,在用ApplicationContext创建Spring 容器时不是有两种方法吗,一种是利用注解核心配置类,也就是
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
还有一种是用ApplicationContext.xml配置,
但是之后想用Spring的ContextLoaderListener创建上下文对象,并存储到域中。视频中教的是用xml文件配置,可是我用的是注解核心配置类,那该怎么写呢,下面是web.xml的代码

img

img

img

  • 写回答

2条回答 默认 最新

  • 程序yang 优质创作者: 编程框架技术领域 2023-02-23 11:00
    关注

    如果想在注解核心配置类中使用Spring的ContextLoaderListener创建上下文对象,并存储到域中,可以通过添加@WebListener注解和实现ServletContextListener接口的方式实现。

    具体步骤如下:

    1.在SpringConfiguration类上添加@WebListener注解,标记该类为监听器。

    2.实现ServletContextListener接口,实现contextInitialized()方法和contextDestroyed()方法。

    3.在contextInitialized()方法中,使用AnnotationConfigWebApplicationContext创建Spring容器,并将其存储到ServletContext域中。

    4.在contextDestroyed()方法中,销毁Spring容器。

    示例代码如下:

    @WebListener
    public class SpringContextListener implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            // 创建Spring容器
            AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
            context.register(SpringConfiguration.class);
            context.refresh();
            // 将Spring容器存储到ServletContext域中
            sce.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            // 销毁Spring容器
            AnnotationConfigWebApplicationContext context =
                    (AnnotationConfigWebApplicationContext) sce.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            context.close();
        }
    }
    
    @Configuration
    @ComponentScan("com.cyf")
    @Import({DataSourceConfiguration.class})
    public class SpringConfiguration {
        // ...
    }
    

    在web.xml中,仍然需要配置ContextLoaderListener监听器:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:com/cyf/config/SpringConfiguration.java</param-value>
    </context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    

    这样,在使用AnnotationConfigApplicationContext创建Spring容器时,也可以通过ContextLoaderListener创建上下文对象,并存储到域中。

    评论

报告相同问题?

问题事件

  • 创建了问题 2月23日