0

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

3
  • You can declare an @Autowired init() method in your @Configuration annotated class and perform any initialization operations in that method. Your 3rd party lib seems to be out of Spring context though, which might be a problem you face down the line. Commented Nov 29, 2014 at 17:33
  • When I do that, I get the following warning in the console: WARNING: Autowired annotation should be used on methods with actual parameters is there specific documentation around autowiring an init method? Commented Nov 29, 2014 at 17:40
  • I am not sure why the warning comes up, but you certainly implement @Bohuslav's solution. Commented Nov 29, 2014 at 17:47

1 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.