programing

Spring Boot에서 로컬 서버 호스트와 포트를 얻는 방법

muds 2023. 3. 27. 21:41
반응형

Spring Boot에서 로컬 서버 호스트와 포트를 얻는 방법

Spring Boot 어플리케이션을 기동합니다.mvn spring-boot:run.

내 것 중 하나@Controller에는, 애플리케이션이 수신하고 있는 호스트 및 포토에 관한 정보가 필요합니다.localhost:8080(또는127.x.y.z:8080Spring Boot 매뉴얼에 따라server.address그리고.server.port속성:

@Controller
public class MyController {

    @Value("${server.address}")
    private String serverAddress;

    @Value("${server.port}")
    private String serverPort;

    //...

}

를 사용하여 응용 프로그램을 시작할 때mvn spring-boot:run다음과 같은 예외가 있습니다.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is 
org.springframework.beans.factory.BeanCreationException: Could not autowire field: ... String ... serverAddress; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'server.address' in string value "${server.address}"

둘다요.server.address그리고.server.port자동 전원을 켤 수 없습니다.

Spring Boot 애플리케이션이 바인딩되어 있는 (로컬) 호스트/주소/NIC 및 포트를 확인하려면 어떻게 해야 합니까?

IP 주소

네트워크 인터페이스를 취득할 수 있습니다.NetworkInterface.getNetworkInterfaces()네트워크 이외의 IP 주소와 함께 반환되는 인터페이스 객체.getInetAddresses()그 후, 이러한 주소의 스트링 표현은,.getHostAddress().

항구

를 작성하면,@Configuration실행하는 클래스ApplicationListener<EmbeddedServletContainerInitializedEvent>, 덮어쓸 수 있습니다.onApplicationEvent포트 번호가 설정되면 가져옵니다.

@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
    int port = event.getEmbeddedServletContainer().getPort();
}

포트 정보는 다음을 통해 얻을 수 있습니다.

@Value("${local.server.port}")
private String serverPort;

적어도 실행 포트를 취득하기 위한 간단한 회피책은 파라미터 javax.servlet을 추가하는 것입니다.컨트롤러 메서드 중 하나의 시그니처에 HttpServletRequest가 포함되어 있습니다.일단 HttpServletRequest 인스턴스가 있으면 request.getRequestURL().toString()과 함께 baseUrl을 가져옵니다.

이 코드를 확인해 주세요.

@PostMapping(value = "/registration" , produces = "application/json")
public StringResponse register(@RequestBody RequestUserDTO userDTO, 
    HttpServletRequest request) {
request.getRequestURL().toString();
//value: http://localhost:8080/registration
------
return "";
}

방금 Eureka 클라이언트 라이브러리를 사용하여 서버 IP와 포트를 쉽게 얻을 수 있는 방법을 찾았습니다.어쨌든 서비스 등록에 사용하고 있기 때문에, 이 목적만을 위한 추가 lib는 아닙니다.

먼저 maven 종속성을 추가해야 합니다.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

다음으로 임의의 스프링콩에서 ApplicationInfoManager 서비스를 사용할 수 있습니다.

@Autowired
private ApplicationInfoManager applicationInfoManager;
...

InstanceInfo applicationInfo = applicationInfoManager.getInfo();

InstanceInfo 개체에는 IP 주소, 포트, 호스트 이름 등 서비스에 대한 모든 중요한 정보가 포함됩니다.

@M의 회답에 기재되어 있는 솔루션 중 하나.Deinum은 내가 많은 Akka 앱에서 사용한 것 중 하나이다.

object Localhost {

  /**
   * @return String for the local hostname
   */
  def hostname(): String = InetAddress.getLocalHost.getHostName

  /**
   * @return String for the host IP address
   */
  def ip(): String = InetAddress.getLocalHost.getHostAddress

}

Oozie가 REST 서비스에 콜백 할 수 있도록 Oozie REST의 콜백 URL을 작성할 때 이 방법을 사용해 왔습니다.

코드의 포토 번호를 취득하려면 , 다음을 사용합니다.

@Autowired
Environment environment;

@GetMapping("/test")
String testConnection(){
    return "Your server is up and running at port: "+environment.getProperty("local.server.port");      
}

이 Spring Boot Environment에서는 환경 속성을 이해할 수 있습니다.

spring-cloud-commons-2.1.0의 spring 클라우드 속성에서 호스트 이름을 가져올 수 있습니다.RC2.jar

environment.getProperty("spring.cloud.client.ip-address");
environment.getProperty("spring.cloud.client.hostname");

spring-cloud-brown-2.1.0의 spring.displaces.displaces.RC2.jar

org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.client.HostInfoEnvironmentPostProcessor

봄 2의 경우

val hostName = InetAddress.getLocalHost().hostName

var webServerPort: Int = 0
@Configuration
class ApplicationListenerWebServerInitialized : ApplicationListener<WebServerInitializedEvent> {
    override fun onApplicationEvent(event: WebServerInitializedEvent) {
        webServerPort = event.webServer.port
    }
}

, 「」도 할 수 .webServerPort★★★★★★★★★★★…

는 그 .application.properties이와 같이(자신의 속성 파일을 사용할 수 있습니다)

server.host = localhost
server.port = 8081

에서는 쉽게 수 .@Value("${server.host}") ★★★★★★★★★★★★★★★★★」@Value("${server.port}")필드 레벨 주석으로 사용합니다.

또는 시스템 속성에서 얻을 수 있는 것보다 다이내믹한 경우

여기 예가 있습니다.

@Value("#{시스템 속성['server])"). (호스트'])
@Value("#{시스템 속성['server])").controll']]")

이 주석을 더 잘 이해하려면 다음 예제를 참조하십시오.@Value 주석의 다중 사용

@Value("${hostname}")
private String hostname;

Property로 되어 Spring-boot 2.3에서 할 수 .시스템 환경 속성, 시스템 환경 속성, 시스템 환경 속성/actuator/env

언급URL : https://stackoverflow.com/questions/29929896/how-to-get-local-server-host-and-port-in-spring-boot

반응형