比方說,我有我的主類這樣的:重複調用Destroy和New Context是否很糟糕?
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()
會給這個例外,
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:使用ClassPathXmlApplicationContext
,而不是一般的方面,我可以調用雖然context.refresh(),沒有錯誤。
爲什麼不直接調用refresh()然後在上下文中,如果你想這樣做? – dunni
我不認爲這可能會導致內存泄漏或任何不好的情況,但這樣做很不常見。通常你爲整個應用程序創建一個應用程序上下文。也許如果你分享用例,我們可以找到更好的解決方案。 –
@dunni我無法調用上下文。刷新(),因爲它給出了一個異常: SEVERE:對目標類[class spring.task.test.TestTasker]調用方法'runTask'失敗 java.lang.IllegalStateException:GenericApplicationContext不支持多次刷新嘗試:只需調用'刷新'一次 –