The most of times is not impossible to start any enterprise project from scratch. The acceptable way is smart refactoring with possible new technologies or techniques usage and improving the code quality which should go hand in hand.
Spring stack (framework, integration, spring-data and more projects supporting dependency injection DI<IoC>) is well know in the enterprise world and it's also excited turning project parts into the Scala world.
Let's show how to use @Autowired annotation to give spring scala controller more responsibility.
1. define example Service
//a. define interface ~ trait trait ExampleImportService { def name: String } ... //b. define class ~ service functionality @Service("exampleImportService") class ExampleImportServiceImpl extends ExampleImportService{ override def name: String = "Imported service over XML" }2. Autowire services with the Controller
@Controller @RequestMapping(Array("/")) class HelloExampleController @Autowired() (exampleService: ExampleService, exampleImportService: ExampleImportService){ private val logger = LoggerFactory.getLogger(getClass) @RequestMapping(method = Array(RequestMethod.GET)) def printMain( model: ModelAndView): ModelAndView = { model.addObject("message", "Here is Scala with ServiceName = " + exampleService.serviceName) model.addObject("importMessage", "Here is Scala with ServiceImportName = " + exampleImportService.name) model.setViewName("main") model } @RequestMapping(method = Array(RequestMethod.GET), value = Array[String]{"/test/web"}) def printTest(model: ModelMap): String = { logger.info("PrintTest Start") "test" } }The controller "HellolExampleController" defines different return types (callbacks -> ModelAndView holder and String) based on specific request handling. Both return types are resolved then by our simple DispatcherServlet configuration.
val servlet: Dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)) servlet.addMapping("/") servlet.setLoadOnStartup(1)The example project uses Java Servlet 3.0 (intro) with interface ServletRegistration.Dynamic and runs on Tomcat 7.x using SBT building tool (next blog post how to enable tomcat(port = 9090))
Let's start and stop:
1. sbt -> container:start 2. sbt -> container:stopand Enjoy spring 4 scala!
project: miko-spring-scala on github
No comments:
Post a Comment