user1860832
user1860832

Reputation: 63

Invoking Spring based application from a shell script outside the container

I have a Spring based application using Hibernate deployed in Tomcat. This works perfectly fine when executed within the container or invoking a servlet residing in Tomcat. It reads all the configuration files such as applicationContext.xml and other hibernate files. But I have to execute a Java main method from a shell script outside the Tomcat environment. So, I created a main method within the WAR file which invokes the respective methods. But I get that applicationContext is null when it is invoked via a script.

ApplicationContext appCtx = ApplicationContextProvider.getApplicationContext();

The shell script as as below

WAR_PATH="/usr/apache-tomcat-6.0.36/webapps/AdminTool/WEB-INF"
CLASSPATH=$WAR_PATH/classes
java -classpath $CLASSPATH:$WAR_PATH/lib/*: com.mycompany.controller.BatchController "$1"

How can I achieve to have the Spring context working invoked through the script?

Many Thanks

Upvotes: 2

Views: 2171

Answers (2)

Apurva Singh
Apurva Singh

Reputation: 5000

Lets say you have a class called Main with a main method. Mark the class with:

@org.springframework.context.annotation.Configuration
@ComponentScan(basePackages = {"com.your_base_package"})
@Component

In the main method, start by:

 ApplicationContext ctx = new AnnotationConfigApplicationContext(Controller.class);
    ctx.getBean(Controller.class).invokeTransformationService(pipelineId);

The @Configuration annotation will process all annotations. The @ComponentScan is needed to tell Spring container the base package where components will be searched. The @Component makes this class a component so that it is retrievable from ApplicationContext. Spring container will use these annotations to look for all @Components, create a singleton(by default singleton) and register it with ApplicationContext.

Upvotes: 0

ch4nd4n
ch4nd4n

Reputation: 4197

You would have to tell your application how to initialize the beanfactory using ApplicationContext. Depending on what version of Spring you are using. In case you are using version 2 refer to documentation


Instantiating a spring container in Spring 3 Documentation

ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

Upvotes: 1

Related Questions