为了学习SpringBoot,将平时学到的记录下来。本文将详细讲述如何在程序一运行就执行指定功能。

1、准备工作

首先,创建一个maven项目,如何创建maven项目请参考:https://blog.csdn.net/chenzz2560/article/details/83270232。在创建完maven项目后,在pom. 中导入SpringBoot运行需要的依赖包。

<?  version=\"1.0\" encoding=\"UTF-8\"?>
<project  ns=\"http://maven.apache.org/POM/4.0.0\"  ns:xsi=\"http://www.w3.org/2001/ Schema-instance\"
         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">
    <modelVersion>4.0.0</modelVersion>

    <groupId>czz.study</groupId>
    <artifactId>commandLineRunner</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.spring work.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.spring work.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.spring work.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>


    <build>
        <plugins>
            <plugin>
                <groupId>org.spring work.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、创建要运行的程序

创建一个class类,里面包含了你要启动运行的方法。@Component 注解将这个类声明为一个Bean对象,交给Spring进行管理。实现CommandLineRunner接口,实现接口中的run方法。这样,只要程序一运行,就会自动运行run中的代码

package czz.study;

import org.spring work.boot.CommandLineRunner;
import org.spring work.stereotype.Component;

@Component
public class TestRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {

        System.out.println(\"初始化运行\");
    }
}

3、运行程序

创建一个启动类,@SpringBootApplication 功能相当于@Configuration,@EnableAutoConfiguration,@ComponentScan这三个注解,SpringApplication.run(Main.class, args)这行代码用来声明项目入口,没有这行代码,使用的Spring注解都会失效(等于没有注解)。

package czz.study;

import org.spring work.boot.SpringApplication;
import org.spring work.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {

    public static void main(String[] args) {

        SpringApplication.run(Main.class, args);
    }
}

4、运行结果

从结果中我们可以看出项目一运行,就执行了打印语句。

\"\"

总结:一个项目中可以有多个实现CommandLineRunner接口的程序,Spring一个个执行它们。

收藏 打印