Как запустить сервер с портом из server.properties, а не yaml - PullRequest
0 голосов
/ 19 февраля 2020

как получить порт сервера из server.properties, а не из .yml?

У меня есть приложение, которое запускается с порта 7799, которое находится в файле .yml в /src/main/resources/

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"));

    }

У меня есть файл server.properties по адресу /config/, в который я помещаю все параметры базы данных.

Как получить порт из server.properties вместо файла .yml?

1 Ответ

0 голосов
/ 19 февраля 2020

Есть несколько способов получить любое значение из файла свойств. Одним из способов является

. У вас может быть отдельный класс, чтобы получить все свойства, чтобы все, что вы получите, было здесь

@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);
    });
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...