• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

kotlin에서 registerBean 컴파일 에러 해결법

23.01.28 14:40 작성 조회수 653

6

kotlin으로 toby님의 강의를 따라다가다 안되는 부분이 발생하여 다른분들도 해결하시면 좋을 것 같아 공유차원에서 글 남깁니다!

 

org.springframwork.context.support.registerBean을 impot하여 해결할 수 있습니다.

관련 docs:

https://docs.spring.io/spring-framework/docs/5.0.0.RELEASE/spring-framework-reference/kotlin.html

 

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory
import org.springframework.boot.web.server.WebServer
import org.springframework.boot.web.servlet.ServletContextInitializer
import org.springframework.context.support.GenericApplicationContext
import org.springframework.context.support.registerBean
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class HellobootApplication

fun main(args: Array<String>) {
      val myApplicationContext = ApplicationContext()
      myApplicationContext.registerSpringBean()

      val serverFactory: TomcatServletWebServerFactory = TomcatServletWebServerFactory()
      val webServer: WebServer = serverFactory.getWebServer(
         ServletContextInitializer {
            it.addServlet("frontController", FrontController::class.java)
               .addMapping("/*")
         }
      )
      webServer.start()
}

class ApplicationContext{

   fun getContext() = springApplicationContext

   fun registerSpringBean(){
      springApplicationContext.apply{
         registerBean<HelloController>()
         refresh()
      }
   }

   companion object{
      val springApplicationContext: GenericApplicationContext = GenericApplicationContext()
   }
}

class FrontController: HttpServlet() {
   override fun service(request: HttpServletRequest?, response: HttpServletResponse?) {
      requireNotNull(request)
      requireNotNull(response)
      val springApplicationContext = ApplicationContext().getContext()
      val helloController = springApplicationContext.getBean(HelloController::class.java)

      //인증, 보안, 다국어, 공통 기능 처리
      duplicateCode()

      if(request.requestURI == "/hello"
         && request.method == HttpMethod.GET.name
      ){
         val name = request.getParameter("name")
         response.status = HttpStatus.OK.value()
         response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
         response.writer.println(helloController.hello(name))
      }else {
         response.status = HttpStatus.NOT_FOUND.value()
      }
   }
}

private fun duplicateCode(){}

답변 2

·

답변을 작성해보세요.

5

공유해주셔서 감사합니다.

0

이민준님의 프로필

이민준

2023.02.26

감사합니다~ 도움이 됐습니다