2011-05-07 60 views
1

Spring提供實用程序Configurer來解析具有外部配置數據的佔位符(有關詳細信息,請參閱文檔)。如何使用Cake Pattern以類似的方式配置組件(即使用外部配置來解析佔位符)?蛋糕圖案和彈簧配置器

例如:

// properties configuration file 

driver=com.mysql.jdbc.Driver 
dbname=mysql:mydb 
user=michael 
password=***** 

trait JdbcSupport { 
    val dataSource:Datasource 
    ... 
} 

trait OrderDAOComponent {self: JdbcSupport => 
    val dao: OrderDAO 
    class OrderDAOImpl extends OrderDAO {...} // use the JDBC data source here 
}

如何使用屬性配置文件中使用Cake Pattern初始化OrderDAO

回答

2
trait XmlConfigJdbcSupport extends JdbcSupport { 
    val xmlFile:String 
    override val dataSource = readConfigAndReturnDatasource() 
} 

object MyContext extends OrderDAOComponent with XmlConfigJdbcSupport { 
    override val xmlFile = "config.xml" 
} 

dataSource應該可能是一個懶惰的val,以避免初始化順序的問題。

+0

我更喜歡一個通用特質'Configurer',它知道如何讀取配置文件並通過鍵返回值。 – Michael 2011-05-07 16:34:34

+0

在這種情況下,你可以這樣做:trait Configurer [A] {def a:A};特質SomeDao {self:Configurer [DataSource] => ...};然後擴展Configurer [DataSource]以提供如何獲取DataSource的實現)並將該特性與SomeDao混合。 – 2011-05-07 17:06:21