scala sbt工程使用spring框架demo

这篇博客展示了如何在Scala中使用Spring框架进行依赖注入和单元测试。代码包括一个`User`类实现了`Person`特质,以及对应的测试类`UserTest`,它通过`ClassPathXmlApplicationContext`加载bean配置并执行测试。`build.sbt`文件列出了项目依赖,而`bean1.xml`配置文件定义了`User` bean。
摘要由CSDN通过智能技术生成

不废话,直接上代码,工程结构如下,主要涉及四个文件或配置:User.scala、UserTest.scala、build.sbt、bean1.xml:

User.scala:

package com.fighter

trait Person {
  def add(): Unit
}

class User extends Person {

  def add(): Unit = {
    println("Hello, world!")
  }

}

UserTest.scala:

package com.fighter

import org.scalatest.FunSuite
import org.springframework.context.ApplicationContext
import org.springframework.context.support.ClassPathXmlApplicationContext

class UserTest extends FunSuite {


  test("auto create class success") {
    val context: ApplicationContext =
      new ClassPathXmlApplicationContext("bean1.xml")

    val user = context.getBean("user").asInstanceOf[User]
    user.add()

  }

  test("auto create class with trait success") {
    val context: ApplicationContext =
      new ClassPathXmlApplicationContext("bean1.xml")

    val user = context.getBean("user").asInstanceOf[Person]
    user.add()

  }
}

build.sbt:

name := "spring5_demo"

version := "0.1"

scalaVersion := "2.12.14"

libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.0" % "test"
libraryDependencies += "org.springframework" % "spring-beans" % "5.3.8"
libraryDependencies += "org.springframework" % "spring-context" % "5.3.8"
libraryDependencies += "org.springframework" % "spring-core" % "5.3.8"
libraryDependencies += "org.springframework" % "spring-expression" % "5.3.8"
libraryDependencies += "commons-logging" % "commons-logging" % "1.2"

bean1.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="user" class="com.fighter.User"></bean>

</beans>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值