spring项目输出当前的activeprofile

springboot spring 文章 2023-05-04 21:08 1303 0 全屏看文

AI助手支持GPT4.0

首先,在你的配置文件中,你需要指定当前的active profile。例如:

spring.profiles.active=dev

这里我将active profile设置为dev,你可以根据实际情况进行修改。


然后,在你的代码中,你可以通过注入Environment对象来获取当前的active profile。例如:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@SpringBootApplication
@Configuration
public class MyApp {
    
    @Autowired
    private Environment environment;
    
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
    
    public void printActiveProfile() {
        String[] activeProfiles = environment.getActiveProfiles();
        if (activeProfiles.length > 0) {
            System.out.println("当前的active profile是:" + activeProfiles[0]);
        } else {
            System.out.println("没有设置active profile");
        }
    }
}

在上面的代码中,我们首先通过@SpringBootApplication注解来标记我们的应用程序,然后通过@Configuration注解来标记一个配置类。在这个配置类中,我们注入了Environment对象,并在printActiveProfile()方法中使用getActiveProfiles()方法来获取当前的active profile,并输出到控制台中。


最后,在main()方法中,我们通过SpringApplication.run()方法来启动我们的应用程序,并可以在需要的地方调用printActiveProfile()方法来输出当前的active profile。


-EOF-

AI助手支持GPT4.0