@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
}
如何从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);
});
}
}
@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
}