2014-09-22 40 views
2

我有一個包含兩個字段一個POGO:如何在Groovy中強制執行bean合約驗證?

class BaseEntity { 
    Long id 
    Long version 
} 

兩個字段必須是正的(既不是0也不是負的)。 爲防止BaseEntity實例被非正面的id /版本值創建(或設置),我需要添加的最小代碼量是多少?

知道我能做到這一點的「老,Java的方式」:

class BaseEntity { 
    private Long id 
    private Long version 

    BaseEntity(Long id, Long version) { 
     super() 

     setId(id) 
     setVersion(version) 
    } 

    Long getId() { 
     // Return a "clone" to preserve the original ID 
     new Long(id) 
    } 

    Long getVersion() { 
     // Return a "clone" to preserve the original version 
     new Long(version) 
    } 

    def setId(Long id) { 
     if(id < 1) { 
      throw new IllegalArgumentException("ID must be positive!") 
     } 

     this.id = id 
    } 

    def setVersion(Long version) { 
     if(version < 1) { 
      throw new IllegalArgumentException("Version must be positive!") 
     } 

     this.version = version 
    } 
} 

...但是這似乎是的樣板代碼很多了Groovy的社區必須有發現身邊的快捷方式......


更新

我每次添加的建議GContracts,然後運行下面的JUnit測試:

@Test 
void id_cannotBeZero() { 
    BaseEntity entity = new BaseEntity() 

    entity.id = 0 
} 

當我運行這個JUnit的不拋出任何類型的異常傳遞

+2

你有沒有看[GContracts(http://gcontracts.org/)? – dmahapatro 2014-09-22 15:00:50

回答

2

使用GContracts象下面這樣:

@Grab(group='org.gcontracts', module='gcontracts-core', version='[1.2.12,)') 
import org.gcontracts.annotations.* 

@Invariant({ id > 0 && version > 0 }) 
class BaseEntity { 
    Long id 
    Long version 
} 
+0

感謝@dmahapatro(+1) - 但是在添加您的建議更改後,這似乎不起作用(請參閱上面的JUnit測試)。 JUnit測試通過的地方(我認爲)它會拋出某種異常......任何想法? – smeeb 2014-09-22 15:55:20

+0

對我來說看起來像一個bug。雖然在構造函數中使用'@ Requires'可以做到這一點(http://paste.ubuntu.com/8404667/)。將更多地研究它。 – dmahapatro 2014-09-22 17:19:26

+0

這不起作用 - 採用「舊Java方式」。 – smeeb 2014-09-23 11:54:03

相關問題