java用spring实现配置文件properties的读取

来源:互联网 发布:网站美工需要会什么 编辑:程序博客网 时间:2024/05/29 02:57

需要使用Spring的两个注解:@Configuration和@Bean

这里我主要写一下用这两个注解来实现对配置文件properties的读取:

新建配置文件system.properties内容如下:

sys.timeSwitch=false

新建SystemConfig.java内容如下:

@Configurationpublic class SystemConfig {    /**     * 读取系统配置文件     *     * @return PropertiesFactoryBean     */    @Bean    public PropertiesFactoryBean systemProperty() {        PropertiesFactoryBean systemProperty = new PropertiesFactoryBean();        systemProperty.setLocation(new ClassPathResource("system.properties"));        return systemProperty;    }}

最后我们可以在其它类中这样使用即可:

/** * 是否允许修改系统时间 */@Value("#{systemProperty['sys.timeSwitch']}")private boolean sysTimeSwitch;/** * 获取当前时间 * * @return 当前时间 */@Overridepublic Calendar getNow() {    if (sysTimeSwitch) {         Calendar c = Calendar.getInstance();        c.add(Calendar.MINUTE, minute);        return c;    } else {        return Calendar.getInstance();    }}

这只是其中的一个方法,还有用xml的办法解析,大家可以下来查查资料。

1 0
原创粉丝点击