Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何从server.properties而不是yaml使用端口启动服务器_Spring_Spring Boot_Properties_Port - Fatal编程技术网

Spring 如何从server.properties而不是yaml使用端口启动服务器

Spring 如何从server.properties而不是yaml使用端口启动服务器,spring,spring-boot,properties,port,Spring,Spring Boot,Properties,Port,如何从server.properties而不是.yml获取服务器端口 我的应用程序从端口7799开始,该端口位于/src/main/resources/中的.yml文件中 public static void main(String[] args) throws UnknownHostException { SpringApplication app = new SpringApplication(Application.class); SimpleCommand

如何从server.properties而不是.yml获取服务器端口

我的应用程序从端口7799开始,该端口位于
/src/main/resources/
中的.yml文件中

public static void main(String[] args) throws UnknownHostException {
        SpringApplication app = new SpringApplication(Application.class);
        SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
        addDefaultProfile(app, source);
        Environment env = app.run(args).getEnvironment();
        log.info("Access URLs:\n----------------------------------------------------------\n\t" +
                "Local: \t\thttp://127.0.0.1:{}\n\t" +
                "External: \thttp://{}:{}\n----------------------------------------------------------",
            env.getProperty("server.port"),
            InetAddress.getLocalHost().getHostAddress(),
            env.getProperty("server.port"));

    }
我在位置
/config/
中有server.properties文件,我将所有数据库参数都放在该位置


如何从server.properties而不是.yml文件获取端口?

有几种方法可以从属性文件获取任何值。 一种方法是

您可以使用一个单独的类来获取所有属性,这样您就可以从这里获取所有属性

@Component
@ConfigurationProperties(prefix = "server")
@PropertySource("classpath:server.properties")
public class ServerProperties {
    private String protocol;
    private String port;
    private String host;

    ...get and set methods here
}
然后在你的课堂上通过

@Autowired
private ServerProperties serverProperties;
获取属性的第二种方法是

private static Properties prop = new Properties();
prop.load(DummyClass.class.getResourceAsStream("/server.properties"));
String port = prop.getProperty("server.port");
获取运行应用程序的端口

@Configuration
public class ServletConfig {
private static Properties prop = new Properties();
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
   prop.load(DummyClass.class.getResourceAsStream("/server.properties"));
   String port = prop.getProperty("server.port");
   return (container -> {
     container.setPort(port);
    });
  }
}

是否可以从属性文件中仅获取端口,并将所有其余端口保留在.yml中?通过第二种方式,您可以从属性文件中仅获取端口值接下来要做什么?我有端口,但我如何实现它的应用程序开始与它?我不想只得到端口。我想用server.properties中的端口号启动我的应用程序。你能试试最后一部分吗