Spring PropertyPlaceholderConfigurer example

Often times, most Spring developers just put the entire deployment details (database details, log file path) in XML bean configuration file as following :



    
        
    
    
        
    
    
        
        
        
        
    

But, in a corporate environment, deployment detail is usually only can ‘touch’ by your system or database administrator, they just refuse to access your bean configuration file directly, and they will request a separate file for deployment configuration, for example, a simple properties, with deployment detail only.

PropertyPlaceholderConfigurer example

To fix it, you can use PropertyPlaceholderConfigurer class to externalize the deployment details into a properties file, and access from bean configuration file via a special format – ${variable}.
Create a properties file (database.properties), include your database details, put it into your project class path.

jdbc.driverClassName=com.mysql.jdbc.Driver  
jdbc.url=jdbc:mysql://localhost:3306/mkyongjava 
jdbc.username=root  
jdbc.password=password

Declare a PropertyPlaceholderConfigurer in bean configuration file and map to the ‘database.properties‘ properties file you created just now.

     
     
        database.properties 
     

Full example



    
        
            database.properties
        
    
    
        
    
    
        
    
    
        
        
        
        
    

Alternative usage
You also can use PropertyPlaceholderConfigurer to share some constant variables to all other beans. For example, define your log file location in a properties file, and access the properties value from different beans configuration files via ${log.filepath}.

你可能感兴趣的:(Spring PropertyPlaceholderConfigurer example)