如何在spring加载应用程序上下文后执行作业?

use*_*458 30 java spring

我想在加载Spring上下文后运行一些工作,但我不知道如何做到这一点.
你知道怎么做吗?

Phi*_*das 22

另一种可能性是将监听器注册到应用程序上下文事件().基本上它与skaffman的解决方案相同,只需实现:

org.springframework.context.ApplicationListener<org.springframework.context.event.ContextRefreshedEvent>
Run Code Online (Sandbox Code Playgroud)

而不是生命周期.它只有一种方法而不是三种方法.:-)

  • 请注意,由于您使用的是Spring MVC,因此您将获得2个刷新事件.有关详细信息,请参阅此帖子:http://stackoverflow.com/questions/6164573/why-is-my-spring-contextrefreshed-event-called-twice/6165557#6165557 (5认同)

Dar*_*lik 16

如果你想在Spring的上下文启动后运行一个作业,那么你可以使用ApplicationListener和事件ContextRefreshedEvent.

public class YourJobClass implements ApplicationListener<ContextRefreshedEvent>{

    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
             // do what you want - you can use all spring beans (this is the difference between init-method and @PostConstructor where you can't)
             // this class can be annotated as spring service, and you can use @Autowired in it

    }
}
Run Code Online (Sandbox Code Playgroud)


ska*_*man 5

您可以编写实现该org.springframework.context.Lifecycle接口的bean类.将此bean添加到您的上下文中,start()一旦该上下文完成启动,该容器将调用该方法.

  • 这不是真的."生命周期"用于显式调用.只有`SmartLifecycle`将由spring框架自动调用. (7认同)

小智 5

使用@PostConstruct注释.您可以组合任何作业属性并保证在加载上下文中运行您的方法.

  • `@ PostConstruct`只保证在这个bean中完成自动装配.如果要调用自动连接依赖项的方法,请不要使用`@ PostConstruct`,因为无法保证在这些依赖项中完成自动装配. (13认同)
  • 值得一提的是它是一个javax注释,而不是Spring特有的注释. (3认同)

use*_*458 2

谢谢大家的回复。事实上,我在问题中遗漏了一些细节,我想在加载应用程序上下文后立即运行 Quartz Job。我尝试了解决方案 stakfeman,但运行 Quartz Job 时遇到了一些问题。最后我找到了解决方案:Use Quartz inside Spring,代码如下:

<!--
        ===========================Quartz configuration====================
    -->
    <bean id="jobDetail"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="processLauncher" />
        <property name="targetMethod" value="execute" />
    </bean>

    <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
        <!-- see the example of method invoking job above -->
        <property name="jobDetail" ref="jobDetail" />
        <!-- 10 seconds -->
        <property name="startDelay" value="10000" />
        <!-- repeat every 50 seconds -->
        <property name="repeatInterval" value="50000" />
    </bean>

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="simpleTrigger" />
            </list>
        </property>
    </bean>
Run Code Online (Sandbox Code Playgroud)

再次感谢您的帮助,如果问题不是很清楚,我深表歉意':(