How to configure a Spring beans with properties that are stored in a database table

前端 未结 3 958
别那么骄傲
别那么骄傲 2020-12-13 04:49

In my project we\'d like to externalize the properties of our Spring managed beans, that is very easy to do with standard Java .properties files, however we want to be able

3条回答
  •  青春惊慌失措
    2020-12-13 05:33

    I'd use a FactoryBean of type that I'd implement using JdbcTemplate. You can then use the generated Properties object with the mechanism.

    Sample code:

    public class JdbcPropertiesFactoryBean
        extends AbstractFactoryBean{
    
        @Required
        public void setJdbcTemplate(final JdbcTemplate jdbcTemplate){
            this.jdbcTemplate = jdbcTemplate;
        }
        private JdbcTemplate jdbcTemplate;
    
        @Required
        public void setTableName(final String tableName){
            this.tableName = tableName;
        }
        private String tableName;
    
        @Required
        public void setKeyColumn(final String keyColumn){
            this.keyColumn = keyColumn;
        }
        private String keyColumn;
    
        @Required
        public void setValueColumn(final String valueColumn){
            this.valueColumn = valueColumn;
        }
        private String valueColumn;
    
        @Override
        public Class getObjectType(){
            return Properties.class;
        }
    
        @Override
        protected Properties createInstance() throws Exception{
            final Properties props = new Properties();
            jdbcTemplate.query("Select " + keyColumn + ", " + valueColumn
                + " from " + tableName, new RowCallbackHandler(){
    
                @Override
                public void processRow(final ResultSet rs) throws SQLException{
                    props.put(rs.getString(1), rs.getString(2));
                }
    
            });
            return props;
        }
    }
    

    XML Configuration:

    
        
            
                
                
            
        
        
        
        
    
    
    
    

提交回复
热议问题