如何从主方法调用组件的方法?

phe*_*mix 3 spring-boot

我是 springboot 的新手

我创建了一个组件:

@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();
    }
    .....
}
Run Code Online (Sandbox Code Playgroud)

这是主要方法:

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

    public static void main(String[] args) {



    }
}
Run Code Online (Sandbox Code Playgroud)

如何从main方法调用组件的方法 process() ?

Pij*_*rek 5

出于测试目的,可以在您的应用程序类中实现 CommandLineRunner 接口。

然后,由于Article是一个 spring bean,您可以自动装配它并简单地调用该方法。

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)