Spring learning notes -- how Spring assembles various types of attributes and Practical Applications

Source: Internet
Author: User

Spring learning notes -- how Spring assembles various types of attributes and Practical Applications

We can assign values to the attributes defined in the class through the Spring container. What is the function of Spring? For example,
If we encrypt the database connection configuration file, we cannot directly load and use it. At this time, we need to first decrypt the configuration file, then, the decrypted value is assigned to a constant class. At this time, we load the attributes in this constant class to connect the database.
The Code is as follows:

    
     
                   
                        
              
                     
            
     
    
   
      
      
          
           
            
             
       
        
         
          
           
          
         
        
       
      
     
    
   
  

Next let's take a look at DecryptPropertyPlaceholderConfigurer

public class DecryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {    private Resource[] locations;             private Resource keyLocation;         private String fileEncoding;     public void setLocations(Resource[] locations){         try {              this.locations = locations;          } catch (Exception e) {            e.printStackTrace();        }    }     public void setKeyLocation(Resource keyLocation){         try {              this.keyLocation = keyLocation;           } catch (Exception e) {            e.printStackTrace();        }    }           public void setFileEncoding(String fileEncoding) {        this.fileEncoding = fileEncoding;    }    public void loadProperties(Properties props) throws IOException{         if (this.locations != null){                        PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();                         for (int i = 0; i < this.locations.length; i++)             {                                 Resource location = this.locations[i];                                 if (logger.isInfoEnabled()){                                         logger.info("Loading properties file from " + location);                                }                                 InputStream is = null;                                 try{                                         is = location.getInputStream();                                         Key key =getKey(keyLocation.getInputStream());                                       is =doDecrypt(key, is);                                         if (fileEncoding != null){                                                propertiesPersister.load(props, new InputStreamReader(                                                       is, fileEncoding));                                        }else{                                                 propertiesPersister.load(props, is);                                        }                 }                             finally{                                       if (is != null){                                               is.close();                                        }                                }                      }                 }        }     /**          * 
  • *
    • Description: [obtain the key based on the stream]
    • *
      • Midified by [modifier] [modification time]
      • */ public static Key getKey(InputStream is){ try{ ObjectInputStream ois = new ObjectInputStream(is); return (Key) ois.readObject(); }catch (Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } /** *
        • *
          • Description: [decrypts Data]
          • *
          * @param key * @param in * @return */ public static InputStream doDecrypt(Key key, InputStream in){ try{ Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] tmpbuf = new byte[1024]; int count = 0; while ((count = in.read(tmpbuf)) != -1){ bout.write(tmpbuf, 0, count); tmpbuf = new byte[1024]; } in.close(); byte[] orgData = bout.toByteArray(); byte[] raw = cipher.doFinal(orgData); ByteArrayInputStream bin = new ByteArrayInputStream(raw); return bin; }catch (Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } }

        After completing the preceding operations, we can directly use constants in the Constant class.
        The above is to assemble common fields through SpringIOC. What if it is of another type? The following describes the assignment methods of the Set, List, Map, and Properties types:
        The configuration file is as follows:

        
                            
                                 
                                      
                   
                    
        First
                                       
                   
                    
        Second
                                       
                   
                    
        Third
                                   
                              
                             
                                 
                                      
                   
                    
        First list element
                                       
                   
                    
        Second list Element
                                       
                   
                    
        Third list element
                                   
                              
                             
                                 
                                      
                   
                    
        Value1
                                       
                   
                    
        Value2
                                       
                   
                    
        Value3
                                   
                              
                             
                 
                                      
                                       
                     
                      
                     
                    
                               
                           
                

        The code of the PersonService class is very simple, as follows:

        public class PersonServiceBean implements PersonService {    private Set
                
                  sets = new HashSet
                 
                  ();    private List
                  
                    lists = new ArrayList
                   
                    ();    private Properties properties = new Properties();    private Map
                    
                      maps = new HashMap
                     
                      (); public Map
                      
                        getMaps() { return maps; } public void setMaps(Map
                       
                         maps) { this.maps = maps; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public Set
                        
                          getSets() { return sets; } public void setSets(Set
                         
                           sets) { this.sets = sets; } public List
                          
                            getLists() { return lists; } public void setLists(List
                           
                             lists) { this.lists = lists; } public void save(){ }}
                           
                          
                         
                        
                       
                      
                     
                    
                   
                  
                 
                

        The test code is as follows:

        @Test public void instanceSpring(){        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");        PersonService personService = (PersonService)ctx.getBean("personService");        System.out.println("========set===========");        for(String value : personService.getSets()){            System.out.println(value);        }        System.out.println("========list===========");        for(String value : personService.getLists()){            System.out.println(value);        }        System.out.println("========properties===========");        for(Object key : personService.getProperties().keySet()){            System.out.println(key+"="+ personService.getProperties().getProperty((String)key));        }        System.out.println("========map===========");        for(String key : personService.getMaps().keySet()){            System.out.println(key+"="+ personService.getMaps().get(key));        }        ctx.close();    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.