栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

如何实现在SpringBoot项目启动类启动时加载运动特定的代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何实现在SpringBoot项目启动类启动时加载运动特定的代码

如何实现在SpringBoot项目启动类启动时加载运动特定的代码呢 有两种方式
为了方便测试效果,先写一个service在启动类进行注入方便我们输出

package com.wyh.test;

import org.springframework.stereotype.Service;


@Service
public class MyService {
        public String startPrint(){
            System.out.println("启动类被运行加载会调用我");
            return "ok";
        }
}
  //注入我们的service方便实用它的方法
    @Autowired
    private MyService myService;

第一种方式 让我们的启动类实现ApplicationRunner接口 重写它的run方法

implements ApplicationRunner

 @Override
    public void run(ApplicationArguments args) throws Exception {
        //在SpringBoot启动类启动时会被调用
        myService.startPrint();
        System.out.println("我是第一种方式,实现ApplicationRunner接口 重写它的run方法");
    }

第二种方式 让我们的启动类实现CommandLineRunner接口 重写它的run方法

implements CommandLineRunner

@Override
    public void run(String... args) throws Exception {
        //在SpringBoot启动类启动时会被调用
        myService.startPrint();
        System.out.println("我是第二种方式,实现CommandLineRunner接口 重写它的run方法");
    }

开启启动类发现控制台成功打印输出

启动类被运行加载会调用我
我是第一种方式,实现ApplicationRunner接口 重写它的run方法
启动类被运行加载会调用我
我是第二种方式,实现CommandLineRunner接口 重写它的run方法

完整的代码如下

启动类

package com.wyh;

import com.wyh.test.MyService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.wyh.mapper") //扫描我们的mapper接口
//
//1.实现ApplicationRunner接口 重写它的run方法
//2.实现CommandLineRunner接口 重写它的run方法
public class WyhApplication implements ApplicationRunner, CommandLineRunner {
    //注入我们的service方便实用它的方法
    @Autowired
    private MyService myService;
    public static void main(String[] args) {
        SpringApplication.run(WyhApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //在SpringBoot启动类启动时会被调用
        myService.startPrint();
        System.out.println("我是第一种方式,实现ApplicationRunner接口 重写它的run方法");
    }

    @Override
    public void run(String... args) throws Exception {
        //在SpringBoot启动类启动时会被调用
        myService.startPrint();
        System.out.println("我是第二种方式,实现CommandLineRunner接口 重写它的run方法");
    }
}

service

package com.wyh.test;

import org.springframework.stereotype.Service;


@Service
public class MyService {
        public String startPrint(){
            System.out.println("启动类被运行加载会调用我");
            return "ok";
        }
}

项目目录

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/590995.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号