How do I execute a method in Spring when the Server is ready?

I have the following problem, I am using Spring-Boot for a small private web project and I want Spring to call the web service when it starts. And at startup, I mean "when my application is ready to process requests."

I already tried implementing ApplicationListener < ContextRefreshedEvent >, but it didn't work because the event happened earlier (i.e. before the embedded server was ready to process the request). Also the options mentioned in this question do not solve this problem.

Now my question is, is there a way to tell Spring to do something after the server is shut down and ready to handle requests?

EDIT (in response to Daniel's answer):

The problem is that I need some injected properties to make this webservice call, and since Spring does not work on static values, this approach is not an option.

My listener, which does what I want, looks something like this too early:



@Component
public class StartupListener implements ApplicationListener{


    @Autowired
    private URLProvider urlProvider;
    @Value("${server.port}")
    private int port;
    @Value("${project.name}")
    private String projectName;

    @Override
    public final void onApplicationEvent(ContextRefreshedEvent event) {
        RestTemplate template = new RestTemplate();
        String url = uriProvider.getWebserviceUrl(this.projectName);
        template.put(url, null);
    }

}

      

SECOND EDIT:

Although this question solves a very similar problem, it seems that I cannot insert into an object because it must have a form constructor (org.springframework.boot.SpringApplication, [Ljava.lang.String;).

It would also be advisable to solve this problem by not creating a spring.factories file, but using annotations.

+3


source to share


2 answers


If I understand what your problem is, you can call the web service on your main application right after it starts.

public static void main(String[] args) {

        new SpringApplication(Application.class).run(args);
        //call the webservice for you to handle...
    }

      



I'm not sure if this is what you want ...

+1


source


You can use annotation in your component @PostConstruct

. eg.

@Component
public class StartupListener {


    @Autowired
    private URLProvider urlProvider;
    @Value("${server.port}")
    private int port;
    @Value("${project.name}")
    private String projectName;

    @PostConstruct
    public final void init() {
        RestTemplate template = new RestTemplate();
        String url = uriProvider.getWebserviceUrl(this.projectName);
        template.put(url, null);
    }

}

      



This will fire after the bean is initialized and auto-setup is done.

0


source







All Articles