顯示具有 Apache Commons 標籤的文章。 顯示所有文章
顯示具有 Apache Commons 標籤的文章。 顯示所有文章

2013年1月23日 星期三

Precondition of Design by Contract

如果在callee裡面要做precondition的話,我們可以使用org.apache.commons.lang3.Validate,在method一開始執行就進行arguments的驗證,並且丟出合理易懂的exception,避免method執行到很後面時才拋出不太容易理解的exception,也減少stack trace的複雜性有助於debug。

2013年1月11日 星期五

Apache Commons DbUtils

這邊我要介紹Apache Commons DbUtils,在官網的介紹如下:

DbUtils is designed to be:
  • Small - you should be able to understand the whole package in a short amount of time.
  • Transparent - DbUtils doesn't do any magic behind the scenes. You give it a query, it executes it and cleans up for you.
  • Fast - You don't need to create a million temporary objects to work with DbUtils.
DbUtils is not:
  • An Object/Relational bridge - there are plenty of good O/R tools already. DbUtils is for developers looking to use JDBC without all the mundane pieces.
  • A Data Access Object (DAO) framework - DbUtils can be used to build a DAO framework though.
  • An object oriented abstraction of general database objects like a Table, Column, or PrimaryKey.
  • A heavyweight framework of any kind - the goal here is to be a straightforward and easy to use JDBC helper library.
通常我們會使用像JPA或Hibernate這類ORM framework來進行database的系統開發,但如果要extend Hibernate的功能,勢必還是需要直接寫JDBC相關的程式,這時候我們就可以用DbUtils來加快開發速度,不需要操作繁瑣的JDBC API,使用簡單的org.apache.commons.dbutils.QueryRunner就可以進行資料庫的操作,而且搭配多樣org.apache.commons.dbutils.ResultSetHandler<T>類別提供type safe,和Spring的JDBCTemplate相較之下更簡潔一些,可以試試看。

2013年1月9日 星期三

Integrate Apache Commons Configuration with Spring

要整合Apache Commons Configuration到Spring中很容易,直接用Commons Configuration API將org.apache.commons.configuration.Configuration物件設定到Spring,成為Spring managed bean就可以了。

原本有個Spring Modules可以直接將Commons Configuration整合成Spring Property Placeholder,但似乎已經被移除了。

以下是利用database做為configuration source的設定方式:
  1. 假設你已經設定好DataSource。
  2. 設定DatabaseConfiguration,記得先開好table。
  3. 代碼:
    import javax.sql.DataSource;
    import org.apache.commons.configuration.DatabaseConfiguration;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    public class SpringGlm3CoreConfiguration {
        @Bean
        @Autowired
        public org.apache.commons.configuration.Configuration databaseConfiguration(DataSource dataSource) {
            return new DatabaseConfiguration(dataSource, "myconfigs", "key", "value");
        }
    }
  4. Inject Configuration bean到其它class中。
  5. 代碼:
    import org.apache.commons.configuration.Configuration;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;

    @Component
    public class Company {

        @Autowired
        private Configuration conf;

        public String getCompanyId() {
            return conf.getString("company-id");
        }
    }
之後若要抽換設定方式,用XML或是properties file都不會影響到其它程式。