ENV SERVER_PORT会自动覆盖springboot的配置吗
时间: 2023-08-10 07:20:26 浏览: 31
是的,当在 Dockerfile 中使用 `ENV` 命令设置环境变量 `SERVER_PORT` 时,它会覆盖 Spring Boot 应用程序中的默认端口配置。
例如,如果在 Dockerfile 中设置:
```
ENV SERVER_PORT=8081
```
则 Spring Boot 应用程序将使用该值作为默认端口,而不是在 `application.properties` 或 `application.yml` 中配置的端口。这意味着,当您在 Docker 容器中启动 Spring Boot 应用程序时,应用程序将侦听 `8081` 端口,而不是默认的 `8080` 端口。
需要注意的是,如果您在启动 Docker 容器时通过 `-p` 参数映射了主机端口到容器端口,那么您需要将容器端口映射到正确的主机端口。例如,如果您在 Dockerfile 中使用 `ENV SERVER_PORT=8081`,则应该使用以下命令来启动容器:
```
docker run -p 8080:8081 myimage
```
这样,容器的 `8081` 端口将映射到主机的 `8080` 端口,您就可以通过 `http://localhost:8080` 访问 Spring Boot 应用程序了。
相关问题
springboot 我在application.yml 中配置 server:port:8889 我怎么在代码里取到
您可以通过在代码中注入`Environment`对象,然后调用`getProperty`方法来获取`application.yml`中的配置信息。示例代码如下:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class AppConfig {
@Autowired
private Environment env;
public int getServerPort() {
return env.getProperty("server.port", Integer.class);
}
}
```
在上面的示例代码中,我们通过`@Autowired`注入了`Environment`对象,并在`getServerPort`方法中调用了`getProperty`方法来获取`server.port`的值。如果`server.port`不存在,则返回`null`。如果您需要返回一个`int`类型的值,则可以使用`getProperty`的重载方法来指定默认值,如`env.getProperty("server.port", 8080, Integer.class)`。
springboot读取配置文件方式
Spring Boot 提供了多种读取配置文件的方式,以下是其中几种常用的方式:
1. application.properties/application.yml:在 src/main/resources 目录下创建 application.properties 或 application.yml 文件,可以在其中设置应用程序的配置信息,例如:
```
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
```
2. @Value 注解:在代码中使用 @Value 注解读取配置信息,例如:
```
@Value("${server.port}")
private int serverPort;
@Value("${spring.datasource.url}")
private String dataSourceUrl;
@Value("${spring.datasource.username}")
private String dataSourceUsername;
@Value("${spring.datasource.password}")
private String dataSourcePassword;
```
3. @ConfigurationProperties 注解:通过 @ConfigurationProperties 注解将配置文件中的属性值注入到 Bean 中,例如:
```
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties {
private String url;
private String username;
private String password;
// getter/setter
}
```
4. Environment 接口:通过 Environment 接口读取配置信息,例如:
```
@Autowired
private Environment env;
int serverPort = env.getProperty("server.port", Integer.class);
String dataSourceUrl = env.getProperty("spring.datasource.url");
String dataSourceUsername = env.getProperty("spring.datasource.username");
String dataSourcePassword = env.getProperty("spring.datasource.password");
```