[英]What's the proper way to add initialization code to a Spring Boot application?
[英]What's the proper entry point for a Spring application?
我正在使用Ant通過XML文件啟動Spring應用程序。 XML文件創建了一些bean並啟用了組件掃描。
一旦初始化Spring容器並創建了所有Spring bean,我顯然需要實際運行應用程序要運行的代碼。 我嘗試將代碼添加到其中一個bean上的@PostConstruct
方法,但這會導致奇怪的問題,因為在整個Spring應用程序完成實例化之前調用了@PostConstruct
。
什么是等效main()
方法在Spring應用程序實際運行你想在Spring容器完成啟動后運行的東西?
Clubbed要在類路徑中的application-context.xml中加載的所有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
}
}
希望能解決您的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.