springBoot怎么在代码里获取自己的启动端口
时间: 2024-03-02 15:53:17 浏览: 16
可以使用Spring Boot提供的Environment接口来获取自己的启动端口。具体代码如下:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class PortGetter {
@Autowired
private Environment environment;
public int getPort() {
return Integer.parseInt(environment.getProperty("local.server.port"));
}
}
```
在上面的代码中,我们注入了Spring Boot提供的Environment接口,并通过getProperty方法获取了当前应用程序的启动端口。
相关问题
springboot 启动类中打印ip 和端口
可以使用以下代码在Spring Boot启动类中打印IP和端口:
```java
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MyApp.class);
Environment env = app.run(args).getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
System.out.println("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\thttp://localhost:{}\n\t" +
"External: \thttp://{}:{}\n" +
"----------------------------------------------------------",
env.getProperty("spring.application.name"),
env.getProperty("server.port"),
ip,
port);
}
}
```
其中,`InetAddress.getLocalHost().getHostAddress()`可以获取本机IP地址,`env.getProperty("server.port")`可以获取Spring Boot应用的端口号。
springboot 启动类中显示端口
在Spring Boot启动类中,可以使用@Value注解来获取配置文件中的端口号,然后在控制台输出该端口号,以便开发人员或运维人员查看。具体代码如下:
```
@SpringBootApplication
public class DemoApplication {
@Value("${server.port}")
private int port;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@PostConstruct
public void init() {
System.out.println("Server started at port " + port);
}
}
```
在上面的代码中,@Value("${server.port}")注解用于获取配置文件中的端口号,然后将其赋值给port变量。@PostConstruct注解表示在启动类初始化完成后执行init()方法,该方法中输出端口号信息。这样,在启动应用时,控制台会显示类似于“Server started at port 808”的信息。