본문 바로가기

Java/Spring Boot

[Spring Boot] 내장 웹 서버 응용 - 다른 웹 서버 사용하기 / 웹 서버 사용하지 않기 / 포트 변경하기

1. 다른 내장 서버 사용하기

spring-boot-starter-web이 spring-boot-starter-tomcat을 가져오기 때문에

pom.xml에서 exclusion으로 tomcat을 제외시켜주고, 사용하려는 내장서버 dependency 추가

 

 

정상적으로 변경되었다면 dependency에 jetty가 보여야 하고

 

 

실행했을 때, Jetty starterd ~ 문구가 출력되어야 함

 

 

 

 

 

 

 

 

 

 

2. 웹 서버 사용하지 않기

의존성에 웹 관련이 들어가 있으면 spring boot는 웹 애플리케이션으로 실행하려고 함

 

① 소스 코드 내에 WebApplicationType.NONE으로 설정해서 웹 서버를 사용하지 않는 방법도 있지만

public static void main(String[] args) { 
    SpringApplication application = new SpringApplication(Application.class); 
    application.setWebApplicationType(WebApplicationType.NONE); 
    
    application.run(args); 
}

 

② application.properties를 사용해서 바꾸는 방법도 있음

spring.main.web-application-type=none

: 웹 서블릿 컨테이너 의존성이 classpath에 있다하더라도 무시하고 none web application으로 실행하고 끝남

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3. 포트 변경

application.properties 에 변경하려는 포트 번호 입력

server.port=8081

 

랜덤 포트 변경 : 랜덤으로 사용할 수 있는 포트 찾아서 띄워줌

server.port=0

 

 

# ApplicationListener<ServletWebServerInitializedEvent> 

: 웹 서버가 생성이 되면 EventListener가 호출이 됨

 

ex) EventListener 역할을 할 Bean을 만듦

import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class PortListener implements ApplicationListener<ServletWebServerInitializedEvent> {

   @Override
   public void onApplicationEvent(ServletWebServerInitializedEvent servletWebServerInitializedEvent) {
      ServletWebServerApplicationContext applicationContext = servletWebServerInitializedEvent.getApplicationContext();
      System.out.println(applicationContext.getWebServer().getPort());
   }
}

 

다음과 같이 Undertow가 실행되었다는 문구가 출력되고, 바로 다음에 포트번호가 출력되는 것을 확인할 수있음

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard

 

스프링 부트 개념과 활용 - 인프런 | 강의

스프링 부트의 원리 및 여러 기능을 코딩을 통해 쉽게 이해하고 보다 적극적으로 사용할 수 있는 방법을 학습합니다., - 강의 소개 | 인프런...

www.inflearn.com

https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.webserver

 

“How-to” Guides

Spring Boot has no mandatory logging dependency, except for the Commons Logging API, which is typically provided by Spring Framework’s spring-jcl module. To use Logback, you need to include it and spring-jcl on the classpath. The recommended way to do th

docs.spring.io