Spring Scala 實踐

項目代碼 http://git.oschina.net/for-1988/Simples

Spring Scala 實踐

Spring Scala 項目是Spring團隊提供的,爲了簡化在 Scala 應用中使用 Spring 框架。咱們相信不少 Spring 用戶想嘗試 Scala,但並不像放棄他們在 Spring 框架上的積累,這個項目就是爲這些人準備的。目前的版本已經1.0.0.RC1,因此打算嘗試一下。Spring Scala項目目前是基於spring 3.2.4.RELEASE 版本開發的 java

使用SBT構建工程

scala的環境以及sbt等相關工具的搭建,這裏就不詳細描述了,網上有很多資料。下面是工程的build.sbt文件的配置 mysql

name := "Spring-Scala-Simple"

version := "1.0"

scalaVersion := "2.10.4"

scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")

resolvers ++= Seq(
  "SpringSource Milestone Repository" at "http://repo.springsource.org/milestone/")

libraryDependencies ++= {
  val springscala = "1.0.0.RC1"
  val springV = "3.2.4.RELEASE"
  Seq(
    "org.springframework.scala" %% "spring-scala" % springscala,
    "org.springframework" % "spring-jdbc" % springV,
    "commons-dbcp" % "commons-dbcp" % "1.4",
    "mysql" % "mysql-connector-java" % "5.1.26",
    "aspectj" % "aspectjweaver" % "1.5.4",
    "org.scalatest" %% "scalatest" % "2.0" % "test",
    "junit" % "junit" % "4.11" % "test")
}

Spring配置

Spring Scala中對spring的配置提供一種經過編碼實現FunctionalConfiguration接口來配置Bean的方式,固然也支持xml的方式。咱們這裏仍然採用的是xml的方法,由於我沒有找到FunctionalConfiguration中如何去配置component-scan。 git

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

	<context:component-scan base-package="com.topteam.services"></context:component-scan>
	<context:component-scan base-package="com.topteam.dao"></context:component-scan>

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<value>classpath:app.properties</value>
		</property>
	</bean>

	<!-- 勤務數據庫配置 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/Simples" />
		<property name="username" value="root" />
		<property name="password" value="11111" />
	</bean>
	
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource">
		</property>
	</bean>
	
	<tx:advice id="txAdviceDuty" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="login" read-only="false" propagation="REQUIRED"/>
            <tx:method name="exist*" read-only="true" propagation="REQUIRED"/>
            <tx:method name="query*" read-only="false" propagation="NOT_SUPPORTED"/>
            <tx:method name="*" read-only="false" propagation="REQUIRED"
                       rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>


    <aop:config proxy-target-class="true">
        <aop:pointcut id="txPointcutDuty"
                      expression="execution(* com.topteam.services..impl..*.*(..))"/>
        <aop:advisor advice-ref="txAdviceDuty" pointcut-ref="txPointcutDuty"
                     order="1"/>
    </aop:config>

	<bean id="jack" class="com.topteam.bean.Person" c:firstName="Jack"
		c:lastName="Doe" />
	<bean id="jane" class="com.topteam.bean.Person" c:firstName="Jane"
		c:lastName="Doe" />
	<bean id="john" class="com.topteam.bean.Person" c:firstName="John"
		c:lastName="Doe">
		<property name="father" ref="jack" />
		<property name="mother" ref="jane" />
	</bean>

</beans>

這裏能夠配置信息跟之前沒有任何區別,若是你的xml中的bean配置須要用到scala的集合。那麼須要在xml文件中添加下面這段配置 spring

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="propertyEditorRegistrars">
        <bean class="org.springframework.scala.beans.propertyeditors.ScalaEditorRegistrar"/>
    </property>
</bean>

這裏配置了數據源、事務以及一些咱們本身編寫的bean。 sql

Bean的注入

1.編寫一個scala的bean shell

class Person(val firstName: String, val lastName: String) {
  var father: Person = _
  var mother: Person = _
}

2.經過配置注入Bean 數據庫

<bean id="jack" class="com.topteam.bean.Person" c:firstName="Jack"
		c:lastName="Doe" />
	<bean id="jane" class="com.topteam.bean.Person" c:firstName="Jane"
		c:lastName="Doe" />
	<bean id="john" class="com.topteam.bean.Person" c:firstName="John"
		c:lastName="Doe">
		<property name="father" ref="jack" />
		<property name="mother" ref="jane" />
	</bean>

3.經過註解注入Bean express

@Service
class PersonService {
  @Autowired @Qualifier("john") var john:Person = _
}
4.單元測試,這裏咱們簡單的寫了個單元測試的父類
trait SpringTestContext {
  lazy val applicationContext =new ClassPathXmlApplicationContext("classpath:spring-context.xml")
}
class SimpleTest extends SpringTestContext{

  @Test
  def beanTest(){
    val person = applicationContext.getBean("john",classOf[Person])
    println(person.father.firstName)  // "Jack"
  }
}

數據庫CRUD

Spring Scala 中目前提供了JdbcTemplate、JmsTemplate、RestTemplate、TransactionTemplate。這塊的目前的文檔都沒有,因此這邊只是試着用了用JdbcTemplate。目前對crud基本沒有作任何封裝,只是用了JdbcTemplate提供的方法。因爲Scala的一些語法特性,這塊能夠作更好的封裝。 apache

trait BaseDao {

  implicit def dataSource: DataSource

  lazy val jdbcTemplate = new JdbcTemplate(dataSource)

}
@Repository
class PersonDao extends BaseDao {

  @Autowired @Qualifier("dataSource") var ds: DataSource = _

  implicit lazy val dataSource = ds

  def findAllPerson: Seq[Person] = {
    def toPerson(rs: ResultSet, i: Int): Person = new Person(rs.getString(1), rs.getString(2))
    jdbcTemplate.queryAndMap("select * from Person")(toPerson)
  }

  def savePerson(person: Person) = {
    jdbcTemplate.updateWithSetter("insert into Person(firstName, LastName) values(?,?)")(ps => {
      ps.setString(1, person.firstName)
      ps.setString(2, person.lastName)
    })
  }
}

下一步嘗試

  • 集成Spring MVC
  • 進一步封裝CRUD
相關文章
相關標籤/搜索