gpt4 book ai didi

java - 重复调用Destroy和New Context是不是不好?

转载 作者:行者123 更新时间:2023-11-30 08:06:25 24 4
gpt4 key购买 nike

假设我的主类是这样的:

public class TestTasker
{
private static GenericXmlApplicationContext context; // to be accessed by static main

public void runTask()
{
System.out.println("Current time is: " + new Date());

context.destroy();
initContext();

// if I do this instead..
// context.refresh();
// I'd get an exception:
// SEVERE: Invocation of method 'runTask' on target class [class spring.task.test.TestTasker] failed
// java.lang.IllegalStateException: GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once

// EDIT2: by using ClassPathXmlApplicationContext instead of generic context,
// I can call context.refresh() with no error.
}

private static initContext()
{
context = new GenericXmlApplicationContext("AppContext.xml");
}

public static void main(String[] args)
{
initContext();
}
}

AppContext.xml:

<?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:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util" 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.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

<!-- Task Scheduler -->
<task:annotation-driven />
<bean id="testTasker" class="spring.task.test.TestTasker" />
<util:properties id="applicationProps" location="application.properties" />
<context:property-placeholder
properties-ref="applicationProps" />
<task:scheduled-tasks>
<task:scheduled ref="testTasker" method="runTask"
cron="#{applicationProps['cron.expression']}" />
</task:scheduled-tasks>

</beans>

application.properties:

cron.expression=*/5 * * * * ?

如果我这样做(重复调用 destroy 和 new context),会产生任何负面后果,例如内存泄漏吗?

还有更好的解决办法吗?我只需要 Spring 自动/定期刷新 AppContext..

编辑:编辑主类中的代码。调用 context.refresh() 会给出此异常,

严重:在目标类 [class spring.task.test.TestTasker] 上调用方法“runTask”失败
java.lang.IllegalStateException:GenericApplicationContext不支持多次刷新尝试:只需调用“刷新”一次

EDIT2:通过使用 ClassPathXmlApplicationContext 而不是通用上下文,我可以调用 context.refresh() 而不会出现错误。

最佳答案

您可以使用 context.refresh();

如果失败,它应该销毁已经创建的单例,以避免悬空资源。换句话说,调用该方法后,要么实例化所有单例,要么根本不实例化。

关于java - 重复调用Destroy和New Context是不是不好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31034107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com