Reputation: 1850
I want to use Tomcat to simply start a service, not a servlet.
I know Tomcat is a servlet container and not an application server, but this is the platform the architect has set for us to use.
I want to have a Java class executed as soon as Tomcat starts up which will load a class from the Spring context and call some method on it.
I'm thinking the best way to do this is to create a Listener which will load my bean from the Spring context using a ClassPathXmlApplicationContext and call the desired method on it.
Is there a better way of doing this ?
Upvotes: 1
Views: 624
Reputation: 85779
You can take advantage of @PostConstruct
annotation. This will execute a method after the bean is created and all the necessary resources have been injected in the bean. This is a sample:
@Service
public class MyBean {
@PostConstruct
public void init() {
//construction logic here...
//printing a message for demonstration purposes
System.out.println("Bean is already created and resources have been injected!");
}
}
To use @PostConstruct
, take into account:
@PostConstruct
.public
, return a void
and have no arguments.Using this approach, you don't need additional listeners in your application.
Upvotes: 1
Reputation: 3166
A lifecycle listener is the standard way to trigger application events based on some Tomcat action (usually Tomcat startup or shutdown). Since your goal is to have a class method invoked on Tomcat startup then it makes the most sense to put this invocation inside a listener. Whether that listener invokes a Spring bean or a simple POJO is arbitrary in terms of which method is better; the answer to that question should be determined by the needs of your application, e.g. will you need the Spring context to make other parts of you application easier to build?
To invoke a Spring bean within a listener you can use the following definitions in your web.xml:
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Upvotes: 1