要把"127.0.0.1:9999"这样的配置写到yml文件中,并使用@Value注解取出来,可以按照以下步骤进行操作:

  1. 在yml文件中添加配置:
myConfig:
  serverAddress: 127.0.0.1:9999
  1. 创建一个配置类,用于读取yml中的配置:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig {
    @Value("${myConfig.serverAddress}")
    private String serverAddress;

    public String getServerAddress() {
        return serverAddress;
    }
}
  1. 在需要使用配置的地方,使用@Autowired注解注入配置类,并使用getServerAddress()方法获取配置的值:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {
    @Autowired
    private MyConfig myConfig;

    public void printServerAddress() {
        String serverAddress = myConfig.getServerAddress();
        System.out.println("Server Address: " + serverAddress);
    }
}

这样,你就可以在MyComponent类中使用myConfig.getServerAddress()方法获取配置文件中的值"127.0.0.1:9999"了

java怎么把127001 9999这样以key喝value形式的配置写到yml里面然后使用Value注解取出来

原文地址: https://www.cveoy.top/t/topic/hIaB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录