`

spring 配置 读取 properties文件 改为 读取数据库

阅读更多

一. 问题

       spring 配置通常读取  .properties 文件;小项目 配置少;分布式项目 配置文件比较多;不容易运维维护;可以改为读取数据库,在数据库维护;

二. Spring 的已有解决方案

    参考:https://www.codeproject.com/articles/28893/loading-application-properties-from-a-database

    

必须的jar包

  • spring.jar (Spring Core) [PropertiesPlaceholderConfigurer]
  • spring-modules.jar (Spring Modules) [CommonsConfigurationFactoryBean]
  • commons-configuration.jar (Commons Configuration) [DatabaseConfiguration]

需要数据库里 有一个表:

For this example, the database has a schema in it called TEST_SCHEMA and a table calledAPPLICATION_PROPERTIES_TABLE with two columns KEY and VALUE*.

TEST_SCHEMA.APPLICATION_PROPERTIES_TABLE

 

 

Spring Configuration

<!-- Required to connect to datasource -->
<bean name="PropertyPlaceholderConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="properties" ref="CommonsConfigurationFactoryBean"/>
</bean>
   
<bean name="CommonsConfigurationFactoryBean"
    class="org.springmodules.commons.configuration.CommonsConfigurationFactoryBean">
       <constructor-arg ref="DatabaseConfiguration"/>
</bean>
   
<bean name="DatabaseConfiguration"
         class="org.apache.commons.configuration.DatabaseConfiguration">
        <constructor-arg type="javax.sql.DataSource" ref="someDataSource"/>
        <constructor-arg index="1" value="TEST_SCHEMA.APPLICATION_PROPERTIES_TABLE"/>
        <constructor-arg index="2" value="KEY"/>
        <constructor-arg index="3" value="VALUE"/>
</bean>

<!-- Included to elaborate functionality -->

<bean name="PropertiesPrinter " class="example.PropertiesPrinter"
     initMethod="displayAllProperties">
    <property name="fileLocation" value="${file.location}"/>
    <property name="petDogsName" value="${pet.dogs.name}"/>
    <property name="keyOne" value="${key.one}"/>
</bean>
<!-- 
 PropertiesPrinter 为测试 类
-->

 三 .自己的方案:

      以上方法是通过commons-configuration  来实现,这种每次读取和变动都会访问数据库,在我们的实际应用中,应该是启动的时候读取一次就可以了,没有必要占着数据库连接,而且全局配置不允许应用修改的。

 

spring 配置:

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
	 <property name="properties"  ref="dataBaseProperties"/>  
    </bean>  
  
   <bean id="dataBaseProperties" class="com.test.common.utils.DatabaseProperties" >  
       <constructor-arg type="javax.sql.DataSource" ref="confDataSource"/>  
       <constructor-arg value="select key_p,value_p from tb_application_properties where type='common' or type='test' "/>  
   </bean>  
   <bean name="confDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">   
     <property name="driverClassName"  value="com.mysql.jdbc.Driver" />  
     <property name="url" value="jdbc:mysql://127.0.0.1:8066/test" />  
     <property name="username" value="test" />  
     <property name="password" value="test" />  
   </bean>  

 

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
/**
 * DatabaseProperties
 * @version 1.0 2016年12月1日
 * @since 1.0
 */
public class DatabaseProperties implements InitializingBean, FactoryBean{

	
	private static final Logger log = LoggerFactory.getLogger(DatabaseProperties.class);  
    private static Properties props = new Properties();  
    private DataSource datasource;  //数据源  
    private String query;  //读取的sql  
  
    public static final String SHIRO_USER_URL = "shiroUserUrl";
    
    public static final String LOCAL_SERVICE = "localService";
    
    public DatabaseProperties(DataSource datasource, String query) {  
        this.datasource = datasource;  
        this.query = query;  
    }  
  
    @Override  
    public void afterPropertiesSet() throws Exception {  
        initProperties();  
    }  
  
    @Override  
    public Object getObject() throws Exception {  
        return props;  
    }  
  
    @Override  
    public Class getObjectType() {  
        return Properties.class;  
    }  
  
    @Override  
    public boolean isSingleton() {  
        return true;  
    }  
  
    private void initProperties() {  
        Connection connection = null;  
        try {  
            connection = datasource.getConnection();  
            PreparedStatement ps = connection.prepareStatement(query);  
            ResultSet rs = ps.executeQuery();  
            while (rs.next()) {  
                String key = rs.getString(1);  
                String value = rs.getString(2);  
                if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {  
                    log.debug("load property. Key=" + key + ",Value=" + value);  
                    props.setProperty(key, value);  
                }  
            }  
            rs.close();  
            ps.close();  
        } catch (Exception e) {  
            log.error(e.getMessage());  
        } finally {  
            if (connection != null) {  
                try {  
                    connection.close();  
                } catch (Exception e) {  
                    log.error(e.getMessage());  
                }  
            }  
        }  
    }  

}

 这样 更灵活,参数在数据库里自己配,项目中可以 调用 DatabaseProperties  Properties props 取得 配置的信息; 

 参考原文博客:

http://blog.csdn.net/maoxiang/article/details/4829553

 

分享到:
评论

相关推荐

    spring读取properties

    ### Spring读取Properties文件的核心知识点 #### 1. **引入PropertyPlaceholderConfigurer** 在Spring的配置文件中,首先需要定义一个`PropertyPlaceholderConfigurer` bean,这是Spring用来解析Properties文件并...

    读取properties文件返回map

    本篇将详细讲解如何在Java中读取`properties`文件并将其内容转换为`Map`对象。 1. **properties文件结构** `properties`文件的结构非常简单,每行代表一个键值对,键和值之间用等号`=`或冒号`:`分隔。例如: ``` ...

    spring读取配置文件

    本篇文章将深入探讨如何在Spring中读取不同目录下的配置文件,以及使用`ClassPathXmlApplicationContext`和`FileSystemXmlApplicationContext`这两种不同的上下文环境来加载它们。 首先,让我们了解`...

    java读取properties文件,连接数据库

    在Java编程中,读取`.properties`文件是常见的任务,这些文件通常用于存储配置信息,如数据库连接参数。本文将详细介绍如何使用Java读取`.properties`文件并利用这些信息连接到数据库。 首先,我们需要理解`....

    spring mvc 读取配置文件

    这篇博客“spring mvc 读取配置文件”将深入探讨如何在Spring MVC中读取和使用配置文件,以及相关工具的应用。 首先,Spring MVC中的配置文件通常是指XML配置文件,如`applicationContext.xml`或`servlet-context....

    java读取properties配置文件

    本文将详细介绍如何在Java中读取`properties`配置文件。 首先,我们需要了解`properties`文件的格式。一个标准的`.properties`文件通常包含多个行,每行由一个键和一个值组成,它们之间用等号(`=`)或冒号(`:`)...

    SSM 读取properties文件

    "SSM 读取properties文件"这个话题聚焦于如何在项目中有效地读取和使用这些配置文件。properties文件通常用于存储应用程序的配置参数,如数据库连接信息、服务器端口、邮件服务设置等,使得这些关键信息能够独立于...

    spring无法读取properties文件数据问题详解

    这时,需要将路径改为 classpath*:config.properties,以便加载所有的配置文件。 例如: ```xml ignore-unresolvable="true" location="classpath:/jdbc.properties, classpath*:/config.properties"/&gt; ``` ...

    Spring Boot多模块配置文件读取

    在Spring Boot应用中,多模块配置文件的读取是一个重要的实践,它有助于提高代码的可维护性和模块化。本文将详细探讨如何在Spring Boot的多模块项目中管理和使用不同的配置文件,以实现低耦合的设计。 首先,了解...

    spring读取jar中的配置文件

    当我们的应用程序被打包成JAR文件后,有时我们需要从JAR内部读取配置文件,例如application.properties或application.yml。本文将深入探讨如何在Spring框架中实现这一功能。 首先,理解Spring的资源配置。Spring...

    Spring 读取properties文件key+value方式.rar

    本教程将深入探讨如何在Spring中以不同的方式读取properties文件,以便更好地理解和应用这些配置。 首先,我们需要一个`application.properties`或`application.yml`文件,其中包含键值对。例如: ```properties ...

    spring-demo09-读取properties配置文件内容.zip

    在`spring-demo09-读取properties配置文件内容`这个示例中,我们可能有一个名为`application.properties`或`config.properties`的文件,存放在项目的`src/main/resources`目录下。这个文件通常包含以下格式的键值对...

    Spring用代码来读取properties文件实例解析

    Spring读取Properties文件实例解析 Spring框架中,读取Properties文件是一个非常重要的步骤,Properties文件中存储着应用程序的配置信息,如数据库连接信息、Server配置信息等。在Spring应用程序中,我们可以使用@...

    定时器(quartz+spring)读取数据库配置

    本教程将深入探讨如何使用Quartz与Spring框架结合来创建一个能从数据库读取配置的定时任务。 Quartz是一个开源的作业调度框架,它提供了丰富的API和功能,可以用来安排和执行任务。Spring框架则是一个全面的企业级...

    Spring3.0 配置文件中加载Properties文件的小例子

    在上面的配置中,`${db.driver}`、`${db.url}`、`${db.username}`和`${db.password}`都是从Properties文件中读取的属性值。Spring会自动替换这些占位符,使得我们的数据源bean能够正确连接到数据库。 除了上述方法...

    Spring配置三种数据源及从属性文件中读取DB连接四要素

    通过属性文件读取数据库连接信息,可以方便地管理和更新数据库配置,同时避免硬编码,提高代码的可维护性。在实际开发中,根据业务场景选择单数据源、多数据源或动态数据源,确保系统的稳定性和扩展性。

    Spring Boot读取配置文件常用方式

    Spring Boot提供了多种方式来读取和使用这些配置文件,使其更加便捷和高效。以下将详细介绍Spring Boot读取配置文件的常用方法。 1. **属性文件** Spring Boot默认支持两种主要的属性文件格式:`application....

    java读取.properties配置文件的几种方法

    总结来说,Java提供了多种方式来读取`.properties`配置文件,包括标准库中的`Properties`和`ResourceBundle`,以及NIO、Spring框架和第三方库如Apache Commons Configuration。选择哪种方式取决于你的具体需求,如...

    java实现properties文件读取

    使用`InputStream`来读取Properties文件,然后调用`load()`方法加载文件内容。这通常在程序启动时进行。 ```java try { InputStream input = new FileInputStream("config.properties"); prop.load(input); } ...

    读取以及修改properties文件

    1. **读取Properties文件** - 使用`java.util.Properties`类:这是Java提供的标准类,用于处理Properties文件。首先,我们需要加载文件到Properties对象中,然后可以通过关键字获取对应的值。 ```java Properties...

Global site tag (gtag.js) - Google Analytics