当前位置: 首页 > 知识库问答 >
问题:

为什么每次访问servlet时都会重新加载Spring应用程序上下文?

陈铭晨
2023-03-14

以下是我问题的相关档案。

日志文件摘录,包括应用程序的启动:

28/11/2012 16:37:48 org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
28/11/2012 16:37:48 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Wed Nov 28 16:37:48 BRST 2012]; root of context hierarchy
28/11/2012 16:37:48 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from URL [file:/C:/bea/user_projects/workspaces/app/target/app-1.0.0/WEB-INF/classes/app-context.xml]
28/11/2012 16:37:48 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [app-data-context.xml]
28/11/2012 16:37:48 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [app-scheduler.xml]
28/11/2012 16:37:48 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [app.properties]
28/11/2012 16:37:48 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@599bcd: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,appDS,job,cronTrigger,org.springframework.scheduling.quartz.SchedulerFactoryBean#0,appDAO,appService,mailerService,appTask, (...)]; root of factory hierarchy
28/11/2012 16:37:50 org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup start
INFO: Starting beans in phase 2147483647

**28/11/2012 16:37:50 org.springframework.scheduling.quartz.SchedulerFactoryBean startScheduler
INFO: Starting Quartz Scheduler now**

28/11/2012 16:37:50 org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 2109 ms

每次调用servlet时出现的日志文件摘录:

<28/11/2012 16h37min50s BRST> <Notice> <WebLogicServer> <BEA-000360> <Server started in RUNNING mode> 
28/11/2012 16:39:06 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@11f7458: startup date [Wed Nov 28 16:39:06 BRST 2012]; root of context hierarchy
28/11/2012 16:39:06 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [app-context.xml]
28/11/2012 16:39:06 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [app-data-context.xml]
28/11/2012 16:39:06 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [app-scheduler.xml]
28/11/2012 16:39:06 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [app.properties]
28/11/2012 16:39:06 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@10ca001: defining beans [(...)]; root of factory hierarchy
28/11/2012 16:39:06 org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup start
INFO: Starting beans in phase 2147483647
**28/11/2012 16:39:06 org.springframework.scheduling.quartz.SchedulerFactoryBean startScheduler
INFO: Starting Quartz Scheduler now**
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <description>generic web.xml</description>

    <!-- ====================================== --> 
    <!--               SPRING                   -->
    <!-- ====================================== --> 
    <!-- Loading Application Bean's. -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:app-context.xml</param-value>
    </context-param>

    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>

   <servlet>
        <display-name>appServlet</display-name>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>br.com.app.publicInterface.appServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/appServlet</url-pattern>
    </servlet-mapping>

</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="locations">
            <list>
               <value>classpath:app.properties</value>
            </list>
       </property>
    </bean>

    <import resource="classpath:app-data-context.xml"/>
    <import resource="classpath:app-scheduler.xml"/>

    <!-- DAOs -->
    <!-- Services -->   
    <!-- tasks -->

</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean name="job" class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass" value="br.com.app.job.QuartzJob" />
        <property name="jobDataAsMap">
            <map>
                <entry key="gerenciadorTasks">
                    <ref bean="gerenciadorTasks" />
                </entry>
            </map>
        </property>
    </bean>

    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="job" />
        <property name="cronExpression" value="${quartz.cronExpression}" />
    </bean>

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="quartzProperties">
            <props>
                <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop>
                <prop key="org.quartz.jobStore.isClustered">true</prop> 
                <prop key="org.quartz.scheduler.instanceName">NotificadorQuartzScheduler</prop>  
                <prop key="org.quartz.scheduler.instanceId">AUTO</prop> 
            </props>
        </property>
        <property name="triggers">
            <list>
                <ref bean="cronTrigger" />
            </list>
        </property>
    </bean>

</beans>
public class AppServlet extends HttpServlet   {

    private static final long serialVersionUID = 7213474106234238692L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter out = resp.getWriter();

        out.println("execução iniciada em: " + new Date());
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:app-context.xml");   
        GerenciadorTasks gt = (GerenciadorTasks) context.getBean(SpringNameBeans.GERENCIADOR_TASKS);
        gt.init();
        out.println("execução terminada em: " + new Date());

    }

}

---根据@Boris的信息,我稍微修改了一下servlet。我的上下文已经加载,我只需要访问它:

public class AppServlet extends HttpServlet   {

    private static final long serialVersionUID = 7213474106234238692L;

    ApplicationContext applicationContext = null;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter out = resp.getWriter();

        out.println("execução iniciada em: " + new Date());
         if (applicationContext == null){
                applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        }
        GerenciadorTasks gt = (GerenciadorTasks) applicationContext.getBean(SpringNameBeans.GERENCIADOR_TASKS);
        gt.init();
        out.println("execução terminada em: " + new Date());

    }

}

共有1个答案

安高义
2023-03-14

在您的代码中,您正在为每个GET方法创建一个新的应用程序上下文,您应该在servlet init()mehod中创建上下文,或者使用Web应用程序root contitt:

public class AppServlet extends HttpServlet   {

@Autowired
ApplicationContext applicationContext;

@Override
public void init(ServletConfig arg0) throws ServletException {
     WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext())
        .getAutowireCapableBeanFactory().autowireBean(this);
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter out = resp.getWriter();

        out.println("execução iniciada em: " + new Date());

        GerenciadorTasks gt = (GerenciadorTasks) this.applicationContext.getBean(SpringNameBeans.GERENCIADOR_TASKS);
        gt.init();
        out.println("execução terminada em: " + new Date());

    }
}

不清楚您的GerenciadorTasks是否是单例的,在我的回答中,我使用了getbean()而不是autowiring。在每个GET请求上调用init()是非常不可能的。另外,请注意,根web应用程序上下文已经在您的配置中使用

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:app-context.xml</param-value>
    </context-param>

    <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>

如果希望在spring中使用调度,请考虑使用相应的API。

 类似资料:
  • 问题内容: 我有一个包含2个测试的测试类: 当我单独运行测试时,我不会出错,但是当我同时运行所有测试时,会失败。失败是由于某些测试修改了应用程序上下文导致的: 是否可以单独运行此测试?我只想在启动test1时读取所有必需的东西,然后运行测试,然后关闭所有必需的东西。然后启动test2。 问题答案: 您可以在修改应用程序上下文的测试类上使用@DirtiesContext批注。 Java文档 Spri

  • 问题内容: 当尝试使用maven构建Web应用程序时,当我的Internet连接处于连接状态时,通常会出现以下错误。 我的问题是,为什么在较早构建同一应用程序时,maven总是每次都要下载。 我的配置每次Maven都要下载时可能出什么毛病? 以下是我尝试离线构建时遇到的错误: 问题答案: 在您的元素(或项目的父级或公司父级POM)中查找该元素。它看起来像下面的样子。 注意元素。该示例告诉Maven

  • 我有一个相当简单的设置。一个包含3个模块的maven项目:core/webapp/model。我正在使用Spring boot来升级我的应用程序。在webapp中,我有一个简单的类WebappConfig如下: 当我部署abcd.war时,applicationcontext加载了两次,并导致以下错误stracktrace: 不存在我前面提到的web.xml。 一些有趣的事情,我不知道为什么: n

  • 问题内容: 据我了解,默认容量为10,并且当其超过10时,它将创建具有新容量的新对象,依此类推。 因此,出于好奇,我输入下面的程序来检查的对象: 根据上述情况,当我未将默认初始容量设置为10时,因此在添加第11个元素时,它将创建一个新对象并增加的容量。 当我打印对象的哈希码时,每次都会给出一个新值。 以下是o / p: 根据默认容量的概念,直到第10个元素之前,都应打印相同的内容,因为在此之前不需

  • 似乎自从我们将tomcat升级到Version8+后,我们在启动时就会重新加载上下文。然而,这似乎只发生在我们的开发环境中(带有eclipse和Tomcat8.5的windows OS)。我们的生产环境(带有Tomcat8.5的linux OS)不存在此问题。我把它贴在下面,但我没有看到任何迹象表明为什么会发生这样的tomcat日志。我知道这是正常的行为,在web应用程序目录中的一些东西被改变,但

  • 我使用spring应用程序上下文安排quartz作业每晚运行。现在,我想为一个已经运行的应用程序更改cron作业,以便它在一小时后运行。我们希望在应用程序上下文中更改cron作业,然后重新启动应用程序以使更改生效。出于安全原因,我们没有访问数据库的权限。 我使用来运行jobDetail并提供一个cron表达式。现在,如果我更改cron表达式并重新启动应用程序,它不会更新实际的cron表达式,因为它