SpringBoot启动自定义方法

一、实现CommandLineRunner接口,重写run方法

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.gzy.demo.NettyClient;

@Component
public class MyStart1 implements CommandLineRunner{

    @Override
    public void run(String... args) throws Exception {
        NettyClient.connect(10007, "127.0.0.1");
    }
}

二、实现ApplicationRunner接口,重写un方法

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.gzy.demo.NettyClient;

@Component
public class MyStart2 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        NettyClient.connect(10007, "127.0.0.1");
    }

}

三、初始化方法加上@PostConstruct注解

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.gzy.demo.NettyClient;

@Component
public class MyStart3{
    @PostConstruct
    public void test() throws Exception {
        NettyClient.connect(10007, "127.0.0.1");
    }
}

四、其他实现思路

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.gzy.demo.NettyClient;

@Configuration
public class MyStart4 {
    @Bean
    public String startNetty() {
        try {
            NettyClient.connect(10007, "127.0.0.1");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "startNetty";
    }
}

About ME

👋 读书城南,🤔 在未来面前,我们都是孩子~
  • 📙 一个热衷于探索学习新方向、新事物的智能产品经理,闲暇时间喜欢coding💻、画图🎨、音乐🎵、学习ing~
👋 Social Media
👋 加入小组~

👋 感谢打赏~