IOC container of Spring core technology (i): Introduction to IOC containers and beans

Source: Internet
Author: User

Recently started studying spring framework, learning the core content of spring today IOC and Bean

1. Introduction to Spring IOC and beans

inversion of Control (IoC) is controlled inversion, also called Dependency Injection (DI) Dependency Injection, Spring implements a complex configuration file-based factory pattern to provide control inversion.

Org.springframework.beans and Org.springframework.context包是Spring中实现IOC的基础包,其中BeanFactory接口提供一套基于配置文件来管理对象类型的机制,ApplicationContext接口继承自BeanFactory接口,除了包含BeanFactory的所有功能之外,在国际化支持、资源访问(如URL和文件)、事件传播等方面进行了良好的支持,而WebApplicationContext是专门针对Web应用。

The application objects managed, instantiated, and assembled by the spring IOC, called Bean,bean, are stored in the spring configuration metadata as dependencies between the beans.

2. Spring IOC Container

  The Org.springframework.context.ApplicationContex interface represents an IOC container that implements the initialization, configuration, and assembly of beans based on configuration metadata, which can be in XML format, Java annotation Format or Java code format.

Common implementations of ApplicationContext interface classes are Classpathxmlapplicationcontext and Filesystemxmlapplicationcontext.

2.1 Spring IOC Configuration instance

To create a applicationcontext based on a configuration file:

New Classpathxmlapplicationcontext (new string[] {"Services.xml", "Daos.xml"});

The Services.xml configuration file format is as follows:

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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" >  <!--Services -  <BeanID= "Petstore"class= "Org.springframework.samples.jpetstore.services.PetStoreServiceImpl">    < Propertyname= "Accountdao"ref= "Accountdao"/>    < Propertyname= "Itemdao"ref= "Itemdao"/>    <!--additional collaborators and configuration for this bean go here -  </Bean>  <!--More beans definitions for services go -</Beans>

The Daos.xml configuration file format is as follows

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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" >  <BeanID= "Accountdao"class= "Org.springframework.samples.jpetstore.dao.ibatis.SqlMapAccountDao">    <!--additional collaborators and configuration for this bean go here -  </Bean>  <BeanID= "Itemdao"class= "Org.springframework.samples.jpetstore.dao.ibatis.SqlMapItemDao">    <!--additional collaborators and configuration for this bean go here -  </Bean>  <!--More beans definitions for data access objects go -</Beans>

You can also use the <import> tag to refer to multiple profiles in a configuration file, as follows

<Beans>    <ImportResource= "Services.xml"/>    <ImportResource= "Resources/messagesource.xml"/>    <ImportResource= "/resources/themesource.xml"/>    <BeanID= "Bean1"class="..."/>    <BeanID= "Bean2"class="..."/></Beans>

2.2. Creating an object using the IOC container

Use the T getbean (String name, Class<t> requiredtype) method in the ApplicationContext interface to create the object instance you want

// Create and configure Beans ApplicationContext context =    new classpathxmlapplicationcontext (new string[] {"Services.xml", "Daos.xml"}); // Retrieve configured instance Petstoreserviceimpl service = Context.getbean ("Petstore", Petstoreserviceimpl.  Class); // Use configured instance List userlist = Service.getusernamelist ();

In fact, our application should not call the Getbean method directly, so it can be completely independent of the Sping API, such as spring and the Web Integration Framework, which can inject objects directly into the controller of the web framework.

3.Bean

The spring IOC container manages a lot of beans, which are created from configuration data, but for the spring IOC container itself, the bean's configuration data is eventually represented by the Beandefinition object. A beandefinition contains the following data: The fully qualified name of the class that the bean corresponds to, the bean's behavior (scope, life cycle, and so on), dependencies to other beans, and other configuration information.

Spring also allows the external objects to be loaded manually, obtaining defaultlistablebeanfactory through the ApplicationContext Getbeanfactory method, Then through the defaultlistablebeanfactory in the Registersingleton (...) or Registerbeandefinition (...) method to load an external object.

Each bean usually has an identifier, and all identifiers cannot be duplicated within the same container, and in an XML configuration, an Bean,id property can be identified with the ID or name class to set only one identifying identity, and the name attribute can have multiple identifiers separated by commas or spaces. You can also leave the ID or name blank, and the container will automatically generate an identifier for the bean. Sometimes, each subsystem wants to access the same bean with a different name, so you can also use the <alias> tag to take an alias for him outside the bean, in the following format:

<name= "Subsystema-datasource"  alias= "Subsystemb-datasource"  /><name= "Subsystema-datasource"  alias  = "Myapp-datasource"/>

Spring can manage any kind of bean, not necessarily the standard JavaBean. The class attribute is used to specify the class for the Bean, as follows:

<id= "Examplebean"  class= "Examples". Examplebean "/><name=" Anotherexample "  class = "examples." Examplebeantwo "/>

3.1 Creating a bean based on the static factory method

If your bean needs to be created according to a specific static factory method, then you can configure this, where the class value of the factory method is located in the class, not the factory method return value of the Class,factory-method specifying the static factory method name

 <  bean  id  = "ClientService"   class  = "examples. ClientService "  Factory-method  =" CreateInstance " />  
 Public class clientservice {  privatestaticnew  clientservice ();   Private ClientService () {}    Public Static ClientService CreateInstance () {    return  clientservice;  }}

3.2 Creating a bean based on the instance factory method

Create a bean's configuration based on the instance factory method, which creates an instance of the factory method based on another bean, using the Factory-bean property to specify the name of the bean where the factory method resides, as follows:

<!--the factory bean, which contains a method called CreateInstance () -<BeanID= "Servicelocator"class= "examples." Defaultservicelocator ">  <!--inject any dependencies required by this locator bean -</Bean><!--The bean to be created via the factory bean -<BeanID= "ClientService"Factory-bean= "Servicelocator"Factory-method= "Createclientserviceinstance"/>
 Public class defaultservicelocator {  privatestaticnew  Clientserviceimpl ();   Private Defaultservicelocator () {}    Public ClientService createclientserviceinstance () {    return  clientservice;  }}

IOC container of Spring core technology (i): Introduction to IOC containers and beans

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.