实际上,仅使用Scala编写Spring-boot Web应用程序并没有什么特别之处,它可以正常工作!
在此博客文章中,我将逐步将基于Java的Spring-boot应用程序完全转换为Scala –可在此github位置获得基于Java的示例– https://github.com/bijukunjummen/spring-boot-mvc-test
首先,我可以选择基于Maven的构建,也可以基于Gradle的构建–我选择了基于Gradle的构建,因为gradle具有出色的scala插件 ,因此对于scala支持,对build.gradle的唯一更改是构建脚本如下:
...
apply plugin: 'scala'
...
jar {
baseName = 'spring-boot-scala-web'
version = '0.1.0'
}
dependencies {
...
compile 'org.scala-lang:scala-library:2.10.2'
...
}
本质上是添加scala插件并指定scala库的版本。
现在,我有一个实体,即Hotel类,它通过Scala转换为以下实体:
package mvctest.domain
....
@Entity
class Hotel {
@Id
@GeneratedValue
@BeanProperty
var id: Long = _
@BeanProperty
var name: String = _
@BeanProperty
var address: String = _
@BeanProperty
var zip: String = _
}
每个属性都带有@BeanProperty注释,以指示scala生成基于Java bean的getter和setter的变量。
将实体放置好后,该实体上用于CRUD操作的Spring数据存储库将转换为:
import mvctest.domain.Hotel;
import org.springframework.data.repository.CrudRepository;
public interface HotelRepository extends CrudRepository<Hotel, Long> {
}
到Scala中的以下内容:
import org.springframework.data.repository.CrudRepository
import mvctest.domain.Hotel
import java.lang.Long
trait HotelRepository extends CrudRepository[Hotel, Long]
以及基于Scala的控制器(使用该存储库列出酒店)–
...
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.stereotype.Controller
import mvctest.service.HotelRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.ui.Model
@Controller
@RequestMapping(Array("/hotels"))
class HotelController @Autowired() (private val hotelRepository: HotelRepository) {
@RequestMapping(Array("/list"))
def list(model: Model) = {
val hotels = hotelRepository.findAll()
model.addAttribute("hotels", hotels)
"hotels/list"
}
}
在这里,HotelRepository的构造函数自动装配就可以了! 请注意为基于构造函数的注入指定@Autowired注释的方式有点尴尬。
最后,基于Spring-boot的应用程序需要一个主类来引导整个应用程序,其中该引导类与Java相似:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class SampleWebApplication {
public static void main(String[] args) {
SpringApplication.run(SampleWebApplication.class, args);
}
}
在scala中,尽管我需要提供两个类,一个用于指定注释,另一个用于引导应用程序,但是可能会有更好的方法(将其归咎于我缺乏Scala的深度!)–
package mvctest
import org.springframework.context.annotation.Configuration
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.ComponentScan
import org.springframework.boot.SpringApplication
@Configuration
@EnableAutoConfiguration
@ComponentScan
class SampleConfig
object SampleWebApplication extends App {
SpringApplication.run(classOf[SampleConfig]);
}
就是这样,通过此设置,整个应用程序都可以正常使用,可以通过以下方式启动该应用程序:
./gradlew build && java -jar build/libs/spring-boot-scala-web-0.1.0.jar
样本端点列出了通过以下URL访问的酒店:http:// localhost:8080 / hotels / list
我在此github位置有完整的git项目:https://github.com/bijukunjummen/spring-boot-scala-web
总之,可以将Scala视为基于Spring-boot的应用程序的一等公民,并且无需特殊配置即可使基于Scala的Spring-boot应用程序正常工作。 就是这样!
翻译自: https://www.javacodegeeks.com/2014/04/spring-boot-and-scala.html