gpt4 book ai didi

java - Spring 应用程序的正确入口点是什么?

转载 作者:行者123 更新时间:2023-12-02 04:17:40 24 4
gpt4 key购买 nike

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

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

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

最佳答案

将所有要加载的 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
}

}

希望能解决您的问题

关于java - Spring 应用程序的正确入口点是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56654134/

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