Spring Learning Series--Chapter III: Configuration of Beans in spring (i)

Source: Internet
Author: User

There are two forms of configuration for spring: XML-based configuration and annotation-based configuration.

There are several ways to configure the Bean:

        1. By means of a full class name, i.e. by reflection;

        2. Through the factory method, there are static factory methods and instance factory methods;

        3. through Factorybean configuration;


configuring beans through XML files

This article describes the XML-based approach to configuring beans in the following directory

    1. JavaBean creation

    2. Configuration of the bean

      1. Xmlbean configuration by means of an XML configuration;

      2. Spring's Dependency injection method

        1. " p> Property Injection

        2. Constructor injection

        3. Factory method injection (rarely used)

    3. Test method   ;

        instantiation of IOC container;

        1. ApplicationContext A simple description of the

      1. Bean Get method

        1. By ID

        2. By type

Using XML to configure beans, you need to complete the bean tag through the bean tag's class attribute to specify the full class name, the id attribute specifies a unique identity that needs to be unique within the IOC container. If it is not specified, spring will automatically define the class of the permission as the ID. In fact, this approach has been used in the first article, "Spring Learning Series-Chapter One: Spring version of HelloWorld", to make a brief summary of this approach.


1, the creation of JavaBean

First create a JavaBean, rewrite the ToString () method to facilitate the test to see the results, this javabean nothing, there is only one property and the corresponding getter and setter method, we all know that when the construction method is not defined, will automatically generate an argument-free construction method.

Package Com.spring.blog.helloworld;public class Hellospring {private string Str;public string Getstr () {return str;} public void Setstr (String str) {this.str = str;} @Overridepublic String toString () {return "hellospring [str=" + str + "]";}}


2. Configure the Bean in the way of XML configuration


A. Configure the bean in the way of XML configuration

Next look at how to configure this bean, below is the content in Applicationcontext.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans.xsd "><!--configuration Springbean--><bean id=" Hellospring "class=" com.spring.blog.helloworld.HelloSpring "><property name=" str "value=" Spring is good! " ></property></bean></beans>

This configuration method has the following features:

      1. Through the bean tag configuration;

      2. The Class property takes the full class name of the Bean, creates the bean in the IOCR container by reflection, and requires an argument-free construction method for the specified classes. You can try to give the Hellospring class only one structure with parameters and test it.

      3. The ID is the bean's identity in the IOC container and needs to be unique.

B, spring relies on the injection method

Attribute injection: The most common way to inject

The above configuration is the method of attribute injection, it should be noted that:name is consistent with setter Method! What do you mean, look at the following code:

The Str property is invariant to the private String str;//setstr to Setstr2public void SetStr2 (String str) {this.str = str;}

The definition of the bean in the relative XML configuration file should be as follows:name is str2, not str

<!--configuration Springbean--><bean id= "hellospring" class= "com.spring.blog.helloworld.HelloSpring" >< Property Name= "str2" value= "Spring is good!" ></property></bean>

Construct method Injection

Create a new Javabean,car class that defines two construction methods:

Package Com.study.spring;public class Car {private string Brand;private string corp;private double price;private int MAXSP Eed;public Car (string brand, String corp, double price) {super (); This.brand = Brand;this.corp = Corp;this.price = Price;} Public Car (string brand, String corp, int maxspeed) {super (); This.brand = Brand;this.corp = Corp;this.maxspeed = Maxspeed; }}

Let's look at how the XML file is configured:

<!--  Configuration by construction method bean  By injecting the property value through the constructor you can specify the position of the parameter (index specified) and the type of the parameter (type specified) for the distinguished constructor  --><!--   using the second construction method  --><bean  id= "Car"  class= "Com.study.spring.Car" ><constructor-arg value= "Audi"  index= "0" > </constructor-arg><constructor-arg value= "Shanghai"  index= "1" ></constructor-arg> <constructor-arg value= ""  index= "2"  type= "Double" ></constructor-arg></bean ><!--   Using the second construction method   --><bean id= "Car2"  class= "Com.study.spring.Car" ><constructor-arg value= "Audi"  type= "java.lang.String" ></constructor-arg>< Constructor-arg value= "Shanghai"  type= "java.lang.String" ></constructor-arg>< Constructor-arg value= ""  type= "int" ></CONSTRUCTOR-ARG></BEAN> 

Through the Bean's Child tag: Constructor-arg is injected into the middle of the object, where the Index property can specify the order of the parameters in the construction method, and type can specify the type of the parameter, so that the constructor to be used is clarified . Consider the overloaded method: A method with the same number of arguments or different parameter types, but with the same name. I think it's understandable here: The Index property here can be likened to the number, and the type attribute analogy to the parameter types.


Interpretation of test methods

This section is analyzed in the following two ways: The first is the instantiation of the IOC container, and the second is how to get the bean?

Next look at the test class:

Package Com.spring.blog.helloworld;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class Main {public static void Main (String [] args) {//Instantiate an IOC container applicationcontext CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml");// Gets the bean instance from the IOC container hellospring hellospring = (hellospring) ctx.getbean ("hellospring");//test Gets the bean instance System.out.println (hellospring);}}


Instantiation of the IOC container

Speaking so much, I've been talking about IOC containers, what exactly is an IOC container?

Spring provides two types of IOC container implementations:

      1. BEANFACTORY,IOC the basic implementation of the container;

      2. ApplicationContext, which provides more advanced features, is the sub-interface of beanfactory, in fact, it is also an interface. Beanfactory is the spring framework infrastructure for spring itself; ApplicationContext for developers using the spring framework, In almost all applications, ApplicationContext is used directly rather than the underlying beanfactory. Regardless of the way, the configuration is the same


Let's take a look at the ApplicationContext class diagram and see that it is an interface, and there are many abstract classes that implement this interface, which has two main implementation classes, One is the classpathxmlapplicationcontext we have used, and the other is filesystemxmlapplicationcontext.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6C/25/wKioL1VA2fXg8rRHAAKXjTs8P8g533.jpg "title=" ApplicationContext organization chart. png "alt=" wkiol1va2fxg8rrhaakxjts8p8g533.jpg "/>

Classpathxmlapplicationcontext: Under the classpath load configuration file, it can be understood that the root directory is SRC, relative to the SRC directory to write the location of the configuration file;

Filesystemxmlapplicationcontext: The file system loads the configuration file. If our configuration file Application-context.xml is placed under the D:/config directory, we can initialize the IOC container through this class, passing in Parameter d:\\config\\application-context.xml.

Configurableapplicationcontext is extended to ApplicationContext, adding two new main methods: Refresh () and close (), allowing ApplicationContext to start, The ability to refresh and close the context.

ApplicationContext instantiates all singleton beans when the context is initialized. This means that all singleton beans will be created regardless of whether you immediately use the BEAN,IOC container registered in the IOC container. In this connection, we can add input statements to the constructor method by providing an argument-free constructor, for example:

Provides an parameterless construction method, the output statement is the public hellospring () {System.out.println ("hellospring ' constructor ...") used for authentication;} Then the main method of the test class only retains the following sentence: ApplicationContext ctx = new Classpathxmlapplicationcontext ("Applicationcontext.xml");

In fact, the following output information can be seen, it is true that when initializing the IOC container, the bean is instantiated:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6C/29/wKiom1VA3a6RtTO4AAMsnNOtMPE504.jpg "title=" All of the singleton bean.png "alt=" wkiom1va3a6rtto4aamsnnotmpe504.jpg "/> are instantiated at initialization time.


How to get a bean

    1. By the ID, that is, when the bean is configured in the XML file, the set ID, the need to enforce the type conversion, the above is used this method;

    2. Obtained by type, the code example is as follows:

Obtained by ID, requires type conversion hellospring hellospring_1 = (hellospring) ctx.getbean ("hellospring");//obtained by type, does not require type conversion, The disadvantage is that when multiple beans of the same type are configured, it is not known which bean to inject, it throws an exception hellospring hellospring = Ctx.getbean (Hellospring.class);


Write here for the time being, about automatic assembly, the inheritance dependency between beans, the scope of the bean, and so on.


Above is their own learning spring some simple records and some personal understanding, if there is wrong place, I hope you can help correct, welcome to discuss.

This article is from "Ace's Dream" blog, please be sure to keep this source http://acesdream.blog.51cto.com/10029622/1640487

Spring Learning Series--Chapter III: Configuration of Beans in spring (i)

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.