不废话,直接上代码,工程结构如下,主要涉及四个文件或配置: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>