Reputation: 5588
As part of the Spring MVC initialization, I need to run an action (just calling a method on a 3rd party library) once as a setup operation. I'm working in Spring MVC environment where I don't really have control over the web.xml or anything, so I can't add a servlet context listener or anything. I tried making an implementation of a WebApplicationInitializer
but it never seems to get called (no idea why though, or how to try and debug that any further).
If I annotate a class with @Configuration
it does get created, so I'm wondering if I can use the class's constructor to perform that setup operation (calling a 3rd party setup method). Is this appropriate/safe to do? Are there any other alternatives for this kind of thing? I'm new to Spring, so I might just be missing something that's meant for this kind of thing.
Thanks
Upvotes: 0
Views: 1467
Reputation: 34776
Configuration class would be an appropriate place to contain some initialization logic. You can place it in a constructor, method annotated with @PostConstruct
or afterPropertiesSet()
method if you implement the InitializingBean
interface for example. The difference is that the constructor code will be called before the beans in your configuration class are instantiated, so if your initialization code depends on some Spring beans, go with the @PostConstruct
/ InitializingBean
approach.
Example:
@Configuration
public class Config {
@PostConstruct
public void initialize() {
// Run some action
}
}
Upvotes: 1