租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

springboot怎么获取yml的值,springboot怎么获取数据库连接

发布时间:2024-03-21 19:57:46

springboot怎样获得yml的值

在Spring Boot中,可以通过在配置文件(如application.yml)中定义属性值,然后在Java代码中使用@Value注解来获得这些属性的值。例如:

在application.yml中定义属性:

app:
  name: My Application
  version: 1.0

在Java类中使用@Value注解获得属性值:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AppConfig {

    @Value("${app.name}")
    private String appName;

    @Value("${app.version}")
    private String appVersion;

    public String getAppName() {
        return appName;
    }

    public String getAppVersion() {
        return appVersion;
    }
}

然后在其他类中可以通过@Autowired注解注入AppConfig类,并调用getAppName()和getAppVersion()方法来获得配置文件中定义的属性值。例如:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Autowired
    private AppConfig appConfig;

    public void printAppInfo() {
        System.out.println("App name: " + appConfig.getAppName());
        System.out.println("App version: " + appConfig.getAppVersion());
    }
}

这样就能够在Spring Boot中通过@Value注解来获得配置文件(如application.yml)中定义的属性值。