Spring Assembly Bean

Source: Internet
Author: User

Spring Assembly Bean Assembly Interpretation: The behavior of creating collaborative relationships between application objects is often referred to as assembly (wiring), which is also an essential dependency injection of dependency injection is the underlying feature of spring one: Introduction to Using Spring assembly Beans 1: declaring beans Bean concept: Beans itself is a large factory, each bean in the beans is equivalent to defining a component, each of which is one of our specific features 1.1: It is important to create spring configuration spring, if spring is not configured, Then it is tantamount to declaring an empty container, meaningless. By configuring the spring container to tell it which beans to load and how to assemble the beans, this ensures that they are collaborating with each other. Spring Container configuration bean: 1: Based on one or more XML configuration files-configuration file configuration (traditional meaning configuration) How to configure 2:java annotations 1.1.1: How to configure XML-based configuration files
1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans xmlns= "Http://www.springframework.org/schema/beans" 3        Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 4        xmlns:context= "http://www.springframework.org/ Schema/context "5        xsi:schemalocation=" Http://www.springframework.org/schema/beans 6/         http Www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/context/HTTP Www.springframework.org/schema/context/spring-context.xsd "7 > 8       9      <bean id=" Mybean "class=" Com.springDemo.beanDemo.BeanIntance "></bean>10 </beans>

In the XML configuration above, we declare a <beans> element that can place all the spring configuration information in it, including the <bean> declaration but in spring, there is not only one beans namespace, Spring provides us with 10 namespaces configured as follows:
    • AOP: Provides configuration information for declaring slices and for class proxies that @aspectj annotations to spring facets
    • Beans: Support for declaring beans and assembly beans, which is the most primitive and core namespace of spring
    • Context: Provides configuration elements for configuring the spring application context, including automatic monitoring and automatic assembly of beans
    • JEE: Provides integration with the Java EE API, such as: Jndi and EJB
    • JMS: Provides configuration elements for declaring message-driven Pojo
    • Lang: Support for configuring beans implemented by scripts such as Grooby,jruby or BeanShell
    • MVC: The ability to enable spring MVC, such as annotation-oriented controllers, view controllers, and interceptors
    • OXM: Supports mapping of spring object to XML configuration
    • TX: Declarative Transaction configuration
    • Util: Provides a variety of tool class elements, including configuring the collection as a bean support property placeholder operation
In the configuration above, the components bound in the,<bean> element specify the Beanintance class in the Com.springDemo.beanDemo package with the ID Mybean The method Mybean in the Beanintance class is injected into the spring container. When the spring container loads the bean, Spring uses the default constructor to instantiate the Mybean Bean, whose internal code is actually:
1 "New com.springDemo.beanDemo.BeanIntance ();" 2 Package Com.springDemo.beanDemo 3   4 public class beanintance{5 public      beanintance Mybean () {beanintance Intanc E = new Beanintance (); Intance.setbeanname = "Bean,...."; Return Intance} 6      private String beanname 7 public      void Setbeanname (String beanname) {  this.beanname = Beann Ame } 8 Public          String Getbeanname () {return  beanname;} 9      10}
Spring is the creation of beans through reflection; When called in a program, we pass the following way:
ApplicationContext CTX = new Classpathxmlapplicationcontext ("Spring-beans.xml"); Load Spring-beans.xml file Beanintance beanintance = (beanintance) ctx.getbean ("Mybean"); Read the Mybean component,
At this point Mybean has returned the Beanintance type (as stated above, it is automatically instantiated at load time here we ctx is equal to a beanintance instance. Getbean ("Mybean") is called the Mybean method. The configuration is injected through the constructor in the bean (in the following code, we add the whole container structure above <beans>, just write out the bean element part configuration)
<bean id= "Mybean" class= "com.springDemo.beanDemo.BeanIntance" >     <constructor-arg value= "Hello"/> </bean>
When we specify the bean element under the <constructor-arg> child element, the spring container is automatically initialized and instantiated to instantiate the string type of the Beanintance class. and assign "Hello" to it.
1 public class Beanintance{2 public      beanintance Mybean () {beanintance intance = new Beanintance (); Intance.setbeannam E = "Bean,...."; Return intance}3      private String beanname;4 public      void Setbeanname (String beanname) {  This.beanname = Beanname; }5 public          String Getbeanname () {return  beanname;} 6 Public          beanintance (String str) {this.beanname = str;} 7}
Inject object reference when the constructor is an object, then we need to define the component of the object in the bean and inject it into our mybean upon invocation. Like what:
<bean id= "Sonbean" class= "com.springDemo.beanDemo.SonBeanIntance"/><bean id= "Mybean" class= " Com.springDemo.beanDemo.BeanIntance ">     <constructor-arg value=" Hello "/>  <constructor-arg ref= "Sonbean"/></bean>
Factory method Static injection spring supports assembling a factory-created bean with the <bean> element amount Factory-method property. If the object being assembled is a static method, you can use Factory-method to invoke the scope of the bean: all spring beans Default to a singleton, that is, only one instance object is created, so that each call will get the same value. If we want to get different values, what do we do to return an instance of the non-pass? Configure the following properties
1 <bean id= "Sonbean" class= "com.springDemo.beanDemo.SonBeanIntance" scope= "ProtoType"/>
    • The scope= "ProtoType" property is for each call to be re-created, except, of course, the bean provides additional scope options after ProtoType, as follows:
    • Singleton: In each spring container, each bean is a unique instance (default)
    • ProtoType: Allows the definition of a bean to be instantiated any time (each invocation creates an instance)
    • Request: In an HTTP request, each bean definition corresponds to an instance that is valid only in a Web-based context such as: Spring MVC
    • Session: In an HTTP session, each bean is defined as an instance that is valid only in a Web-based context such as: Spring MVC
    • Global-session: In a global HTTP session, each bean is defined as an instance that is valid only in the context of the portlet (the Portlet is a Java-based Web Component, managed by the Portlet container, and processed by the container for request , production of dynamic content)
Bean attribute Injection: see example:
1 Pulic class student{2      private String name;3 public      void SetName (String name) {this.name = name;} 4 Public      String GetName () {return this.name;} 5      private int age;6 public      void Setage (int. age) {This.age=age;} 7 Public      int Getage () {return this.age;} 8}
1 <bean id= "Getstudentinfo" class= "com.springDemo.beanDemo.Student" >2      <property name= "name" value= " Liming "/>3      <property name=" age "value="/>4 </bean>
In the bean configuration XML above, we injected a string value for the bean from the bean's element <property> value, noting that the property does not limit the type of value injected in our value, Value can be injected with: Int,float,string,double,bool, so when we inject age value, type int is also auto-aware. One of the injected internal Beanjava is called the Inner class, which is the class in the classes. Then the internal bean is the bean in the bean.
1 <bean id= "Getstudentinfo" class= "com.springDemo.beanDemo.Student" >2      <property name= "name" value= " Liming "/>3      <property name=" age "value=" "/>4 <property name=      " Teacher ">5 <bean           class = "Com.springDemo.beanDemo.Teacher" >6      </property>7 </bean>
Here teacher is created as an internal bean and passed as a parameter to the constructor of student. Internal beans are only available for one injection and cannot be used by other beans, so the internal bean does not have an ID. And the outside is going to call it using Spring's namespace p assembly properties spring's namespace p gives us a way to assemble another bean property so that you don't need to add too many angle brackets. As follows:
1 <?xml version= "1.0" encoding= "UTF-8"?> 2 <beans xmlns= "Http://www.springframework.org/schema/beans" 3        Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 4        xmlns:p= "http://www.springframeword.org/schema/p" > 5     <bean id= "Getstudentinfo" class= "com.springDemo.beanDemo.Student" 6      p:name= "liming" 7      p.age= " "8      p.teacher-ref=" Teacher "9/>10 </beans>
P is a concise notation provided by spring. p.teacher-ref= "Teacher" will use a bean with ID teacher as reference to assemble the teacher attribute-ref suffix as an identity to inform spring that it should assemble a reference instead of a literal Assembly collection: In the previous example, we demonstrated the individual properties in spring and the assembly of objects, so how do you configure a collection class when you have multiple properties or objects? Spring provides us with 4 types of collection configuration elements
    • <list>: Assemble the value of the list type, allowing duplicates
    • <set>: Sets the value of set type, does not allow repetition
    • <map>: Assemble the value of the map type, name and value allow type
    • <props>: The value of the assembly properties type, both the name and the value must be of type string
When an assembly type is an array or collection type, then list and set are useful <map> and <props> corresponding Java map and properties instances are as follows:
1 <bean id= "Getstudentinfo" class= "com.springDemo.beanDemo.Student" >2      <property name= "Studentlist" >3      <list>4           <ref bean= "Getteacherinfo"/>5 <ref bean=           "Getfirststudnetinfo"/>6           <ref bean= "Getscondstudentinfo"/>7      </list>8      </property>9 </bean>
The list contains more than one element, and ref is used to define other bean references in the spring context. A collection of the other list types can also be assembled with set, but make sure that the data in the list is unique.
1 <bean id= "Getstudentinfo" class= "com.springDemo.beanDemo.Student" >2      <property name= "Studentlist" >3      <set>4           <ref bean= "Getteacherinfo"/>5 <ref bean=           "Getfirststudentinfo"/>6           <ref bean= "Getsecondstudentinfo"/>7      </set>8      </property>9 </bean>
Assemble a Map collection:
1 <bean id= "Getstudentinfo" class= "com.springDemo.beanDemo.Student" >2      <property name= "Studentlist" >3      <map>4           <entry key= "Getteacher" value-ref= "Getteacherinfo"/>5           <entry key= " Getfirsestudent "value-ref=" Getfirststudentinfo "/>6           <entry key=" getsecondstudent "value-ref=" Getsecondstudentinfo "/>    7      </map>8      </property>9 </bean>
<map> element declares a value of type Java.util.map, each entry element defines a member of a map, the key property defines the value of entry, the Value-ref attribute defines the value of entry, and references the values of other beans in the context. There are additional properties in entry to specify the key and value
    • Key: Specifies that the value of entry in map is string
    • Key-ref: Specifies that the value of entry in map is a reference to another bean in the spring context
    • Value: Entry value in map specified as String
    • Value-ref: Specifies that the value of entry in map is a reference to other beans in the spring context
Assembly Properties collection If the Map key value pair You are configuring is a string, you can use properties instead of properties,properties to provide the same functionality as map, but it must be a string type to qualify key-value pairs
1 <bean id= "Getstudentinfo" class= "com.springDemo.beanDemo.Student" >2      <property name= "Studentlist" >3      <props>4           <prop key= "Getteacher" >getteacherinfo "</prop>5           <prop key=" Getfirsestudent>getfirststudentinfo</prop>6           <prop key= "Getsecondstudent" > Getsecondstudentinfo "</prop>7      </props>8      </properties>9 </bean>
    • <property> elements are used to introduce values or beans into the bean's properties
    • The <props> element is used to define a collection value for a Java properties type
    • The <prop> element is used to define the members in the </prop> element
With an expression assembled in the front assembly bean, all the values have been determined when we develop the programming code, but when the values we assemble for the property are only available at runtime to know what to say? Spring3 introduced the Spring expression language (Spring Expressions Language, Spel) Spel as a powerful, concise way to assemble beans, It assembles the values into the bean's properties and constructor parameters by executing an expression at run time. Using the Spel, you can achieve an unimaginable assembly effect, which is difficult to achieve using the traditional spring approach. The use features of the SPEL include:
    • Using the Bean's ID to refer to the bean
    • Invoking methods and accessing properties of an object
    • Arithmetic, relational, and logical operations on values
    • Regular expression Matching
    • Collection operations
The primary goal of the Spel fundamentals Spel is to compute a value by arithmetic. In the process of calculating this value, other values are used and the values are manipulated. Literal value:
1 <bean id= "Getstudentinfo" class= "com.springDemo.beanDemo.Student" >2      <property name= "Studentlist" >3      <props>4           <prop key= "Getteacher" >getteacherinfo "</prop>5           <prop key=" Getfirsestudent>getfirststudentinfo</prop>6           <prop key= "Getsecondstudent" > Getsecondstudentinfo "</prop>7      </props>8      </properties>9 </bean>
The property assembles this value into the bean by using the #{} qualifier in value. Reference Bean,properties and Method 1: Reference bean non-spel reference
<property name= "Student"  ref= "Getstudent"/>
Spel references in the above Spel expression, #{getteacher.getname} Getteacher is the Bean's id,getname for the attribute under that ID is visible. It is possible to directly. Out of the properties, methods, objects of the <property name= "name" value= "#{getteacher.getname ()?. Getage ()} "/&GT;?. Indicates whether the preceding getname () is null and then executes the following getage otherwise it will be reported as abnormal. In Spel, the action class uses T () to invoke the method and constant of the class scope <property name= "multiplier" value= "# (T (Java.lang.Math). PI) ">t (Java.lang.Math) Returns an object of type Math. You can also call a static method using T
<property name= "multiplier" value= "# (T (Java.lang.Math). Random ()) ">
Numeric operations can also be performed in an expression <property name= "Add" value= "#{counter.tatol + 2}" ><property name= "Add" value= "#{counter.tatol -2} "><property name=" Add "value=" #{2 * T (Java.lang.Math). Random () + counter.tatol-2} "><property name=" Add "value=" #{str1 + "" + str2} "> for string Connection comparison values: <property name=" Equal "value=" #{a+b==100}> true if value is true to assemble to equal

Spring Assembly Bean

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.