Property injection details in Spring

  • 2020-05-10 18:16:56
  • OfStack

This article demonstrates the injection of int, String, array, list, set, map, Date, and so on.
The injection of Date type is implemented with the help of the property editor provided by Spring, starting with the five entity classes


package com.jadyer.model; 
import java.util.Date; 
import java.util.List; 
import java.util.Map; 
import java.util.Set; 
/** 
 *  Injection of common properties  
 * @see  including int,String,Array,list,set,map,Date The injection of  
 */ 
public class Bean11 { 
  private Integer intValue; 
  private String strValue; 
  private String[] arrayValue; 
  private List listValue; 
  private Set setValue; 
  private Map mapValue; 
  private Date dateValue; 
  /* 7 The properties of the setter and getter slightly  */ 
} 
 
 
package com.jadyer.model; 
public class Bean22 { 
  private Bean33 bean33; 
  private Bean44 bean4422; // Injection: property name independent, with setBean44() The relevant  
  private Bean55 bean55; 
  /* 3 The properties of the setter and getter slightly  */ 
} 
 
 
package com.jadyer.model; 
public class Bean33 { 
  private Integer id; 
  private String name; 
  private String sex; 
  /* 3 The properties of the setter and getter slightly  */ 
} 
 
 
package com.jadyer.model; 
public class Bean44 { 
  private Integer id; 
  private String name; 
  private String sex; 
  private Integer age; 
  /* 4 The properties of the setter and getter slightly  */ 
} 
 
 
package com.jadyer.model; 
public class Bean55 { 
  private String password; 
  /*  about password the setter and getter slightly  */ 
} 

Then we have our custom java.util.Date type converter


package com.jadyer.util; 
 
import java.beans.PropertyEditorSupport; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
 
/** 
 * java.util.Date Property editor. Equivalent to a type converter. Here is the String to Date type  
 * @see ---------------------------------------------------------------------------------------- 
 * @see  This example is mainly for you to know Spring There is also a mechanism for this, rather than having you write a property editor later  
 * @see  The odds of needing to write a property editor are too small, just know that Spring A similar mechanism would be fine  
 * @see ---------------------------------------------------------------------------------------- 
 * @see  The so - called property editor is the Spring The string in the configuration file is converted to the corresponding Java object  
 * @see Spring The built-in 1 Property editor, you can also customize the property editor  
 * @see  Custom property editor things that must be inherited PropertyEditorSupport Class and write setAsText() methods  
 * @see  Finally, the custom property editor is injected into the Spring Can be,  
 * @see ---------------------------------------------------------------------------------------- 
 */ 
public class UtilDatePropertyEditor extends PropertyEditorSupport { 
  private String pattern; // Put the format of the transformation into the configuration file, and let Spring Injection in  
  public void setPattern(String pattern) { 
    this.pattern = pattern; 
  } 
   
  @Override 
  public void setAsText(String text) throws IllegalArgumentException { 
    System.out.println("======UtilDatePropertyEditor.setAsText()======" + text); 
    try { 
      Date date = new SimpleDateFormat(pattern).parse(text); 
      this.setValue(date); // Note: here's what you put in 1 a java.util.Date Object, so the output time is the default format  
    } catch (ParseException e) { 
      e.printStackTrace(); 
      throw new IllegalArgumentException(text); // Continue to throw up parameter illegal exception  
    } 
  } 
} 

The applicationContext-beans.xml file used for all entity classes


<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation=" 
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" 
      default-lazy-init="true"> 
  <!-- default-lazy-init="true" Properties are explained in detail InjectionTest.java Class first 49 line  --> 
  <!-- default-autowire="byName or byType" , this is Spri0ng Automatic assembly provided bean Two ways byName and byType And, a slightly  --> 
   
  <!-- *********************** 【 LAZY==== Delayed initialization *********************************************************************** --> 
  <!--  perform testInjection22() Will be output by default ======UtilDatePropertyEditor.setAsText()======2010 years 06 month 04 day  --> 
  <!--  It is not set at this time default-lazy-init="true" , which suggests that Bean11 In the dateValue The value of the property is injected  --> 
  <!--  In fact, by default Spring When creating a ApplicationContext All objects in the configuration file are instantiated and injected  --> 
  <!--  The advantage of this is if Spring Some of the configuration files are miswritten, and it can detect them immediately  --> 
  <!--  while Struts1.X Configuration file, if a class is written wrong, is not a problem, only in the actual execution, will be a problem  --> 
  <!--  for Spring You can also defer the initialization of the configuration file with the associated properties, i.e default-lazy-init="true" --> 
  <!--  That is, only really use the time, then go New This object, and then you inject the property. This is where it comes in LAZY , that is, delayed initialization  --> 
  <!--  Only need to modify Spring Configuration files can be used, such as <beans xsi:schemaLocation="http://www...." default-lazy-init="true"> --> 
  <!--  In this case, the scope is the entire configuration file, as well as the individual <bean> Of the label lazy-init Properties are configured separately  --> 
  <!--  but 1 It's not usually set like this, it's set like this BeanFactory At the time of creation, the injection is completed, which also makes it easy to check for errors  --> 
  <!-- ***************************************************************************************************************** --> 
   
  <bean id="bean11" class="com.jadyer.model.Bean11"> 
    <property name="intValue" value="123"/><!--  When injected, string 123 It will automatically convert to int type  --> 
    <property name="strValue" value="Hello_Spring"/> 
    <property name="arrayValue"> 
      <list> 
        <value>array11</value> 
        <value>array22</value> 
      </list> 
    </property> 
    <property name="listValue"> 
      <list> 
        <value>list11</value> 
        <value>list22</value> 
      </list> 
    </property> 
    <property name="setValue"> 
      <set> 
        <value>set11</value> 
        <value>set22</value> 
      </set> 
    </property> 
    <property name="mapValue"> 
      <map> 
        <entry key="key11" value="value11"/> 
        <entry key="key22" value="value22"/> 
      </map> 
    </property> 
    <property name="dateValue" value="2010 years 06 month 04 day "/><!--  Here, Date Format should be with applicationContext-editor.xml Same configuration  --> 
  </bean> 
   
  <bean id="bean22" class="com.jadyer.model.Bean22"> 
    <property name="bean33" ref="bean33"/> 
    <property name="bean44" ref="bean44"/> 
    <property name="bean55" ref="bean55"/> 
  </bean> 
   
  <bean id="bean55" class="com.jadyer.model.Bean55"> 
    <property name="password" value="123"/> 
  </bean> 
</beans> 

The applicationContext-common.xml file used for the common entity class


<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation=" 
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
       
  <!--  Use of abstraction bean Extract the common configuration  --> 
  <!--  First of all specified <bean> Of the label abstract Properties for true And then in the others <bean> Specified in the parent Can be  --> 
  <bean id="AbstractBean" abstract="true"> 
    <property name="id" value="2"/> 
    <property name="name" value=" Kylin zhang "/> 
    <property name="sex" value=" male "/> 
  </bean> 
  <bean id="bean33" class="com.jadyer.model.Bean33" parent="AbstractBean"/> 
  <bean id="bean44" class="com.jadyer.model.Bean44" parent="AbstractBean"> 
    <property name="age" value="26"/> 
  </bean> 
</beans> 
 
<!--  use AbstractBean Before the bean33 and bean44 The prototype is as follows  --> 
<!--  
<bean id="bean33" class="com.jadyer.model.Bean33"> 
  <property name="id" value="100"/> 
  <property name="name" value=" zhang 3"/> 
  <property name="sex" value=" male "/> 
</bean> 
<bean id="bean44" class="com.jadyer.model.Bean44"> 
  <property name="id" value="100"/> 
  <property name="name" value=" zhang 3"/> 
  <property name="sex" value=" male "/> 
  <property name="age" value="90"/> 
</bean> 
 --> 

The applicationContext-editor.xml file used for the java.util.Date property editor


<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation=" 
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
       
  <bean id="utilDatePropertyEditor" class="com.jadyer.util.UtilDatePropertyEditor"> 
    <property name="pattern" value="yyyy years MM month dd day "/> 
  </bean> 
   
  <!--  See the source that in CustomEditorConfigurer Of the class 131 Line provides 1 a setCustomEditors Method, so you can inject it  --> 
  <bean id="customEditors" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> 
    <property name="customEditors"> 
      <map> 
        <entry key="java.util.Date" value-ref="utilDatePropertyEditor"/> 
      </map> 
    </property> 
  </bean> 
</beans> 
 
<!--  You can also use the inside <bean> the utilDatePropertyEditor Written in the internal  --> 
<!--  So it has the right to use it, and it doesn't have the right to use it externally  --> 
<!--  No outside access is provided, so inside <bean> There is no id attribute  --> 
<!--  The sample is as follows  --> 
<!--  
<bean id="customEditors" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> 
  <property name="customEditors"> 
    <map> 
      <entry key="java.util.Date"> 
        <bean class="com.jadyer.util.UtilDatePropertyEditor"> 
          <property name="pattern" value="yyyy years MM month dd day "/> 
        </bean> 
      </entry> 
    </map> 
  </property> 
</bean> 
 -->

 

Finally, unit test classes written using JUnit 3.8


package com.jadyer.junit; 
 
import junit.framework.TestCase; 
 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
import com.jadyer.model.Bean11; 
import com.jadyer.model.Bean22; 
 
public class PropertyInjectionTest extends TestCase { 
  private ApplicationContext factory; 
 
  @Override 
  protected void setUp() throws Exception { 
    /****==== Read a single 1 Configuration file ====****/ 
    //factory = new ClassPathXmlApplicationContext("applicationContext.xml"); 
     
    /****==== Multiple configuration files are read using arrays ====****/ 
    // This will treat the two configuration files as 1 One for use, ostensibly as two for use  
    // The inside is actually doing 1 So in multiple configuration files, inside id Can't repeat  
    // but name Attributes can be repeated, just as the difference between a person's id number and name is 1 The sample of  
    //String[] configLocations = new String[]{"applicationContext.xml", "applicationContext-editor.xml"}; 
    //factory = new ClassPathXmlApplicationContext(configLocations); 
     
    /****===== using  *  The matching pattern reads multiple configuration files ====****/ 
    // industry-popular 1 Convention over configuration  
    // So when there is 1 A series 1 You can take advantage of the capabilities provided by the framework to reduce the amount of configuration  
    // Also: if not read applicationContext-*.xml Even if it exists applicationContext.xml It won't read either  
    factory = new ClassPathXmlApplicationContext("applicationContext-*.xml"); 
  } 
 
  /** 
   *  This method demonstrates the injection of common properties, including int,String,Array,list,set,map,Date The injection of  
   * @see  Among them Date Type injection is done with the help of Spring Property editor to implement  
   */ 
  public void testInjection11() { 
    //Bean11 bean11 = new Bean11(); // If a simple new , then its properties will not be injected. The premise of injection must be from IoC You take it out of the container, you inject it  
    Bean11 bean11 = (Bean11)factory.getBean("bean11"); // At this time bean11 Is from IoC So its dependencies are all injected  
    System.out.println("bean11.intValue=" + bean11.getIntValue()); 
    System.out.println("bean11.strValue=" + bean11.getStrValue()); 
    System.out.println("bean11.arrayValue=" + bean11.getArrayValue()); 
    System.out.println("bean11.listValue=" + bean11.getListValue()); 
    System.out.println("bean11.setValue=" + bean11.getSetValue()); 
    System.out.println("bean11.mapValue=" + bean11.getMapValue()); 
    System.out.println("bean11.dateValue=" + bean11.getDateValue()); 
  } 
   
  /** 
   *  The main demonstration of this approach is to abstract the common configuration to reduce the amount of configuration  
   */ 
  public void testInjection22() { 
    Bean22 bean22 = (Bean22)factory.getBean("bean22"); 
    System.out.println("bean22.bean33.id=" + bean22.getBean33().getId()); 
    System.out.println("bean22.bean33.name=" + bean22.getBean33().getName()); 
    System.out.println("bean22.bean33.sex=" + bean22.getBean33().getSex()); 
    System.out.println("bean22.bean44.id=" + bean22.getBean44().getId()); 
    System.out.println("bean22.bean44.name=" + bean22.getBean44().getName()); 
    System.out.println("bean22.bean44.sex=" + bean22.getBean44().getSex()); 
    System.out.println("bean22.bean44.age=" + bean22.getBean44().getAge()); 
    System.out.println("bean22.bean55.password=" + bean22.getBean55().getPassword()); 
  } 
} 

Related articles: