pheromix
pheromix

Reputation: 19287

How to call a component's method from the main method?

I m new to springboot

I created a component :

@Component
public class Article {

    File xml = new File(Constante.ARTICLE_XML);
    static File out = new File(Constante.ARTICLE_CSV + "out_article.csv");

    public synchronized void process() throws IOException, InterruptedException {

        Thread th = new Thread() {
            @Override
            public void run() {
                try {
                    .....
                }
            }
        };
        th.start();
    }
    .....
}

Here is the main method :

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.axian.oxalys.*")
@PropertySource({"file:${app.home}/application.properties"})
public class App {

    public static void main(String[] args) {



    }
}

How can I call the component's method process() from the main method ?

Upvotes: 5

Views: 13177

Answers (2)

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44665

If your goal is to have some logic running on startup, you can create a new bean, implementing either the CommandLineRunner or ApplicationRunner interface. This will automatically execute the run() method on startup, and you don't have to do anything else. For example:

@Bean
public CommandLineRunner runOnStartup(Article article) {
    return args -> article.process();
}

If you explicitly want to call a method within your main method (you probably shouldn't), then you can do so by obtaining a reference to the Environment. Normally if you have a Spring boot application, you have a SpringApplication.run() statement already, which you can use like this:

public static void main(String[] args) {
    ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
    Article article =  context.getBean(Article.class);
    article.process();
}

Upvotes: 4

Pijotrek
Pijotrek

Reputation: 3021

For testing purposes it's okay to implement CommandLineRunner interface in your application class.

Then, since Article is a spring bean, you can autowire it and simply call the method.

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.axian.oxalys.*")
@PropertySource({"file:${app.home}/application.properties"})
public class App implements CommandLineRunner {

    @Autowired
    private Article article

    public static void main(String[] args) {
        SpringApplication.run(App.class, args)
    }

    @Override
    public void run(String... args) throws Exception {
        article.process();
    }
}

Upvotes: 7

Related Questions