Saturday, December 7, 2013

Java Web App with Spring annotations, programmatic web.xml, programmatic application context and a scheduler

Create a new Maven Project with Eclipse

Make sure to flip the packaging to war

Add the following dependencies to your pom

Create the programmatic web.xml. I called mine can call it anything you want)
and stuck it in a package called "conf" under src/main/java

I also created a index.html file just to make sure I can deploy the app at this point and that WebInit kicks in.

Create the programmatic Spring Application Context. I did mine under the same "conf" package and called it SpringAppContext(you can call it anything you want)

Now we have to nudge Spring at app start-up and tell it to start wiring things up - creating beans, injecting and stuff (this is very technical language...thank you!)
So we add the following magic to the programmatic web.xml( in my case):

At this point we redeploy to test:
Search for "testBean" in the console - should be on line indicating it was instantiated by Spring - if that is the case, life is good!

INFO: Pre-instantiating singletons in defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,springAppContext,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,testBean]; root of factory hierarchy
Dec 07, 2013 8:14:47 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 423 ms

Now we do some coding

We create a Service class that would be invoked to do some work from the scheduled job

Then we create the Scheduled Job and Autowire the Service into it:

Now we just have to tell Spring where to look for "@Component"s and also that we want to do scheduling stuff,
so we add these two to our

@ComponentScan(basePackages= {"app"})

"app" is just the name of my base package. For you it would be whatever package you placed your "@Component"s at.

This what the final version of the looks like:

At this point we can deploy and test the complete web app.

And here is a zip of the project: webapp-scheduled

Hope this is useful!

No comments:

Post a Comment