sptingboot---项目启动时自动执行方法

博客介绍了在SpringBoot中实现启动执行的两种接口方式,即ApplicationRunner和CommandLineRunner,指出除可接受参数不同外,二者其他方面大同小异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在SpringBoot中,有两种接口方式实现启动执行,分别是ApplicationRunner和CommandLineRunner,除了可接受参数不同,其他的大同小异

CommandLineRunner :

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


@Component
public class StartMethod implements CommandLineRunner {

    
    @Override
    public void run(String... args) throws Exception {
      //具体的执行方法
    }
}

ApplicationRunner :

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

@Component
public class StartMethod implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments var1) throws Exception{
       //具体的执行方法
    }
}

 

### SpringBoot 中配置启动参数以设置文件编码为 UTF-8 在 SpringBoot 中,可以通过多种方式配置启动参数以设置文件编码为 `UTF-8`。以下是具体的实现方法: #### 1. **通过 JVM 系统变量设置** 可以通过在启动时添加 `-Dfile.encoding=UTF-8` 参数来设置 JVM 的文件编码为 UTF-8。这种方式的优先级高于配置文件中的变量[^1]。 ```bash java -Dfile.encoding=UTF-8 -jar your-springboot-app.jar ``` #### 2. **通过命令行参数设置** 如果使用的是命令行启动 SpringBoot 应用程序,可以直接在命令行中添加启动参数。命令行参数的优先级高于配置文件和 JVM 系统变量[^1]。 ```bash java -jar your-springboot-app.jar --file.encoding=UTF-8 ``` #### 3. **通过配置文件设置** 在 `application.properties` 或 `application.yml` 文件中,可以设置默认的文件编码。不过需要注意,这种方式的优先级低于 JVM 系统变量和命令行参数。 - **application.properties** ```properties file.encoding=UTF-8 spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true ``` - **application.yml** ```yaml spring: http: encoding: charset: UTF-8 enabled: true force: true ``` #### 4. **通过 IDE 配置** 如果是在开发环境中使用 IDE(如 IntelliJ IDEA 或 Eclipse),可以在运行配置中添加 `-Dfile.encoding=UTF-8` 参数。 - **IntelliJ IDEA**: 1. 打开运行配置(Run/Debug Configurations)。 2. 在 VM options 中添加 `-Dfile.encoding=UTF-8`。 - **Eclipse**: 1. 右键项目 -> Run As -> Run Configurations。 2. 在 Arguments 标签下,VM arguments 中添加 `-Dfile.encoding=UTF-8`。 #### 5. **通过 Docker 容器设置** 如果将 SpringBoot 应用程序部署到 Docker 容器中,可以在 `docker run` 命令中添加环境变量或 JVM 参数。 ```bash docker run -e JAVA_OPTS="-Dfile.encoding=UTF-8" your-springboot-image ``` #### 6. **微服务环境下的配置** 在微服务架构中,通常需要根据不同的环境(如开发、测试、生产)选择合适的配置。可以通过 `spring.profiles.active` 参数结合 `-Dfile.encoding=UTF-8` 来实现环境隔离和编码设置[^3]。 ```bash java -Dfile.encoding=UTF-8 -Dspring.profiles.active=prod -jar your-springboot-app.jar ``` ### 注意事项 - 设置 `-Dfile.encoding=UTF-8` 参数时,确保操作系统支持 UTF-8 编码。 - 如果使用的是 Linux 系统,建议检查系统的默认编码是否为 UTF-8。如果不是,可以通过以下命令修改: ```bash export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值