【问题标题】:Spring how to execute methodSpring如何执行方法
【发布时间】:2012-02-29 07:12:24
【问题描述】:

我知道这个问题与Execute method on startup in spring 重复。但是,我已经尝试了在该问题的已接受答案中发布的建议,但对我没有任何帮助。因此,我怀疑虽然这里问的是同一个问题,但我强烈认为根本原因不同,因此需要不同的答案/解决方案。

我试图让 Spring 在启动时创建一个 bean 并立即执行它的方法之一。

我的弹簧配置(heartbeat-config.xml):

<beans (all the xmlns stuff here ommitted for brevity)>
    <bean id="heartbeat" class="org.me.heartbeat.Heartbeat"/>
</beans>

还有Heartbeat.java:

public class Heartbeat
{
    @PostConstruct
    public void start()
    {
        System.out.println("I should see this message in the logs somewhere!!");
    }
}

最后,我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

    <!-- The display name of this web application -->
    <display-name>Heartbeat</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/heartbeat-config.xml</param-value>
    </context-param>

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

当我在 Tomcat 中运行它时,我没有收到任何启动错误。 Tomcat 看起来运行良好(从日志中我可以看出)。但是,在我的start() 方法中,我没有看到应该由System.out 调用生成的日志中的任何输出(Tomcat 将所有标准输出重定向到其日志文件)。

我在这里忽略了什么吗?我可以进行明显的诊断吗?

【问题讨论】:

  • 您需要告诉我们您尝试其他问题的解决方案时发生了什么,否则我们不知道如何以不同的方式回答,这仍然是重复的。
  • 或者你不能从构造函数中执行这个吗?
  • 啊,我对另一个问题所做的唯一更改是添加 @PostConstruct 注释。无论哪种方式,结果都相同,因此该解决方案对我不起作用,而对另一个提问者起作用。
  • flurdy 我的其他选择是什么?你可以发布一个例子吗?谢谢!
  • 不确定是否是解决方案,但 ContextLoader 的 API 文档使用 WEB-INF/applicationContext.xml,而不是 /WEB-INF/applicationContext.xml。没有前导斜线。您能否在 Heartbeat 构造函数中进行一些调试以查看它是否已实例化(或者甚至在调试模式下启动 tomcat)。

标签: java spring tomcat dependency-injection


【解决方案1】:

最简单的方法是忘记注释并将您的 bean 定义更改为:

<bean id="heartbeat" class="org.me.heartbeat.Heartbeat" init-method="start"/>

如果你想要注释,你需要声明上下文命名空间并将其放入你的 applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <!-- Enable @PostConstruct, @PreDestroy and friends in Spring -->
    <context:annotation-config/>

    <bean id="heartbeat" class="org.me.heartbeat.Heartbeat"/>
</beans>

注意:检查命名空间,它们是从网上复制粘贴的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2015-12-10
    相关资源
    最近更新 更多