Spring IOC Foundation

Source: Internet
Author: User
Tags instance method

1.1. Introduction to Spring IOC

 The IOC (inversion of control ) container is responsible for object creation, object storage , object Management, and the core function is to control reversed.

2.1 Spring IOC Programming Introduction Implementation

The Spring IOC project builds the basic steps:

  1. Create a maven project
  2. AddSpringDependent(Spring-context)and configuration Files(Spring-configs.xml)
    <Dependency>      <groupId>Org.springframework</groupId>      <Artifactid>Spring-context</Artifactid>      <version>4.3.9.RELEASE</version></Dependency><Dependency>          <groupId>Junit</groupId>          <Artifactid>Junit</Artifactid>          <version>4.12</version></Dependency>

  3. Writing and configuring Java Classes
  4. Write unit test Initialization container , get java object
3. Spring Framework Components IOC basic application 3.1   Basic configuration of Bean objects

all objects managed by Spring in a software application are called beans

Class, a Java object that conforms to the following rules is called a bean

      1. Property privatization
      2. Must have no parameter constructor
      3. The serialization interface must be implemented
      4. The Bean property with the GetXXX setxxx method declaration

we create our own if required by Spring management First configure this class , Common configuration methods have two , a based on Xml configure An annotation-based configuration

 Package beans;  Public class HelloService {        public  HelloService () {        System.out.println ("HelloService created ");    }    }

When you configure an XML-based object Bean object, you first need to declare the bean type in spring's core configuration file using the bean tag, with an identity of the bean specified by the id attribute. Specify the specific type of bean by the class attribute (must write the full class name)

class= "beans. HelloService "></bean>
 Public classTestBeans01 {PrivateClasspathxmlapplicationcontext ApplicationContext; @Before Public voidinit () {//initializing the SPRING-IOC containerApplicationContext =NewClasspathxmlapplicationcontext ("Spring-configs.xml"); } @After Public voiddestroy () {applicationcontext.close (); } @Test Public voidTestsayhello () {HelloService HelloService= Applicationcontext.getbean ("HelloService", HelloService.class);
System.out.println (HelloService); }

The output is:

How to build 3.2 Bean Object

The building of Bean objects in Spring provides several ways to do this :

1) directly through the construction method

2) Pass the static factory method of the class (for example, the getinstance method of the calendar)

class= "Java.util.Calendar" factory-method= "getinstance" ></bean>
    @Test    publicvoid  Testbeangetmethod () {        = Applicationcontext.getbean ("Calendar", Calendar.  Class);        SYSTEM.OUT.PRINTLN (calendar);    }

3) build the object from an instance method of the instance ( For example , get The date object through the GetTime method of the Calendar object ).

<!-- Spring会调用calendar对象的getTime方法创建对象 -->
class= "Java.util.Date" factory-bean= "Calendar" factory-method= "GetTime" ></bean>
    @Test    publicvoid  Testbeangetmethod () {        = Applicationcontext.getbean ("date", date. ) Class);        SYSTEM.OUT.PRINTLN (date);    }

4) through the Factory instance method

1. Declare a class to be produced by the factory

 Package beans;  Public class MyObject {}

2. Create a factory class to implement the Factorybean interface

 Public classObjectfactoryImplementsFactorybean<myobject>{     PublicMyObject GetObject ()throwsException {System.out.println ("GetObject ()"); return NewMyObject (); }    /*** When this method is called: * 1. When a new object is created * 2. Container closed, Issingleton returns True*/     PublicClass<?>Getobjecttype () {System.out.println ("Getobjecttype ()"); returnMyObject.class; }/*** Returns true for single case * returns false for multiple cases*/     Public BooleanIssingleton () {System.out.println ("Issingleton ()"); return false; }}

3. Configuring the Bean in the spring configuration file

class= "beans. Objectfactory "></bean>

4. Testing

@Test/*** Issingleton Returns true in case output: * Issingleton () * GetObject () * [email protected]        * [email protected] * Issingleton () * Getobjecttype () * Issingleton return flase case OUTPUT: * Issingleton () * GetObject () * [email protected] * Issingleton () * Getobje CT () * [email protected] * Issingleton ()*/     Public voidtestobjectfactory () {MyObject objectFactory1= Applicationcontext.getbean ("Objectfactory", MyObject.class);        System.out.println (ObjectFactory1); MyObject ObjectFactory2= Applicationcontext.getbean ("Objectfactory", MyObject.class);    System.out.println (ObjectFactory2); }    

5. Handing objectfactory to spring management can actually produce MyObject objects for us, but if you want to get objectfactory objects, you need to prefix "&" in front of them.

    @Test    publicvoid  Testobjectfactorybean () {        = Applicationcontext.getbean ("&objectfactory", Objectfactory.  Class);        System.out.println (bean);    }
Scope of the 3.3bean object

Bean objects that are managed in the spring container can be declared with scope properties or related annotations, most commonly singleton,prototype. The meaning is as follows

1) Singleton (global uniqueness of the object identified by this scope): system default

2) prototype (the object identified by this scope will create a new object every time it gets fetched)

     <id= "HelloService"            class= "Beans". HelloService "            scope=" singleton "/>
the life cycle of a 3.4bean object

In the Spring Framework application, all of the bean objects have a life cycle, the so-called Bean object life cycle refers to the creation of bean objects, initialization, service, destruction of the process.

The Bean's life cycle method can be specified in the spring configuration file through the Init-method,destory-method property. For example:

 <  bean  id  = "HelloService"   class  = "beans. HelloService "  scope  =" prototype " Span style= "COLOR: #ff0000" > Init-method  = "init"   Destroy-method  =" destory " />< /span> 
    1. Singleton Object Singleton (single case)

      • Create: When the spring container is initialized, a singleton object is created, and if the Init-method property is set, the initialization method is called after the object is created.
      • Use: Each time the Getbean is called, the same object is returned
      • Destroy: Spring automatically destroys the singleton when the spring container is closed, and if the Destroy-method attribute is specified, the Destroy method is executed before it is destroyed.
    2. Multi-instance object prototype (prototype)

      • Create: When the Getbean method is called, the object is created, and if the Init-method property is set, the initialization method is called after the object is created.
      • Use: Every time Getbean is called, the new object is returned
      • Destroy: Spring no matter!!! Nor does it call Destroy-method!!!
lazy loading of 3.5bean objects

in the Spring Framework application, when the container is initialized, all the bean objects managed by spring are built by default. However, if these objects are not used for a long time, they also occupy the memory, which will cause some waste of resources. To solve this problem,

A lazy loading mechanism is provided in spring. This mechanism is used to improve the efficient use of system resources. Lazy loading in spring requires the Lazy-init attribute in the bean element or the default-lazy-init= "true" of the beans element property to set.

Different points of the two:

1) Lazy-init: Applies to the bean tag to specify the load policy for this bean.

2) Default-lazy-init: Applies to the beans tag to specify the load policy for all beans.

<id= "HelloService"            class= "Beans". HelloService "            scope=" Singleton "            lazy-init=" true "/ >

Spring IOC Foundation

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.