I'm using Ant to launch a Spring application via an XML file. The XML file creates a few beans and enables component-scan.
Once the Spring container is initialized and all of the Spring beans are created, I obviously need to actually run the code that the application is meant to run. I tried adding the code to a @PostConstruct
method on one of the beans, but that causes weird problems because @PostConstruct
is called before the entire Spring application is finished being instantiated.
What's the equivalent of a main()
method in a Spring application to actually run the stuff you want to run after the Spring container has finished starting up?
Clubbed all the xml that you want to load inside an application-context.xml located in the classpath
For example : 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>
Load all the xml using in custom MyBeanLoader using the application-context.xml
public class MyBeanLoader {
public static void main(String args[]){
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
}
}
Now make this as a starter main class file in the 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>
If you want to run the logic after Spring's context start, you can use the ApplicationListener and the event ContextRefreshedEvent.
@Component
public class StartupApplication implements
ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// call you logic implementation
}
}
Hope that will solve your problem
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.