작성
·
769
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(){}