原本有個Spring Modules可以直接將Commons Configuration整合成Spring Property Placeholder,但似乎已經被移除了。
以下是利用database做為configuration source的設定方式:
- 假設你已經設定好DataSource。
- 設定DatabaseConfiguration,記得先開好table。
- Inject Configuration bean到其它class中。
代碼:
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");
}
}
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");
}
}
代碼:
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");
}
}
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");
}
}