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

问题描述 投票:0回答:1

如何从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文件获取端口?

如何从server.properties而不是.yml获取服务器端口?我有从端口7799开始的应用程序,该端口位于/ src / main / resources / public static void main(...)中的.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); }); } }

spring spring-boot properties port
1个回答
0
投票
@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 }
© www.soinside.com 2019 - 2024. All rights reserved.