【问题标题】:What's the proper entry point for a Spring application?Spring 应用程序的正确入口点是什么?
【发布时间】:2019-06-18 17:18:45
【问题描述】:

我正在使用 Ant 通过 XML 文件启动 Spring 应用程序。 XML 文件创建了一些 bean 并启用了组件扫描。

一旦 Spring 容器初始化并创建了所有 Spring bean,我显然需要实际运行应用程序要运行的代码。我尝试将代码添加到其中一个 bean 上的 @PostConstruct 方法中,但这会导致奇怪的问题,因为在整个 Spring 应用程序完成实例化之前调用了 @PostConstruct

什么相当于 Spring 应用程序中的 main() 方法在 Spring 容器完成启动后实际运行您想要运行的内容?

【问题讨论】:

  • 在@SpringBootApplication注解的类的main方法中SpringApplication.run(Application.class, args);之后呢?还是你的应用没有spring boot?
  • 我没有使用@SpringBootApplication,我只有一个XML文件,它定义了一些spring bean并启用了组件扫描。
  • 你没有Java类文件?
  • 我有一堆 Java 类,它们是 @Components,但不,我没有任何运行整个应用程序的主 Java 文件或类似的东西。事实上我根本没有main() 方法...

标签: java xml spring spring-boot ant


【解决方案1】:

将所有要加载的 xml 加入到位于类路径中的 application-context.xml 中

例如:application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC  "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

    <import resource="classpath:DataSourceContext.xml"/>
    <import resource="classpath:HibernateContext.xml"/>
    <import resource="classpath:PropertyContext.xml"/>

</beans>

使用 application-context.xml 在自定义 MyBeanLoader 中加载所有 xml

public class MyBeanLoader {

    public static void main(String args[]){
        ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    }
}

现在将其作为 ant.xml 中的起始主类文件

<target name="jar">
    <mkdir dir="build/jar"/>
    <jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
        <manifest>
            <attribute name="Main-Class" value="com.MyBeanLoader"/>
        </manifest>
    </jar>
</target>

如果要在 Spring 的上下文启动后运行逻辑,可以使用 ApplicationListener 和事件 ContextRefreshedEvent。

 @Component
 public class StartupApplication implements 
 ApplicationListener<ContextRefreshedEvent> {

 @Override
 public void onApplicationEvent(ContextRefreshedEvent event) {
    // call you logic implementation
}

}

希望能解决你的问题

【讨论】:

  • 嗯,我想这是解决问题的一种方法。 spring 框架中真的没有任何注释或任何东西会在spring初始化完成后发出一个类/方法来执行的信号吗?
  • 可以使用ApplicationListener接口,重写onApplicationEvent方法
猜你喜欢
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多