Spring Introduction and IOC

Source: Internet
Author: User
Tags sql error tag name

This section highlights:

    • About Spring
    • Spring Features
    • Spring Frame composition
    • IOC and DI Concepts
    • How the spring framework is introduced into the project

1 Spring Introduction

Spring: The implication brings spring to the software industry, presented by Rod Johnson

Objective: To solve the complexity of enterprise application development.

Scope: any Java application.

Put forward the idea: make the existing technology more practical, not to repeat the wheel, so that the existing framework to use more reasonable. There is no link between struts and hibernate, and all of spring's initial goal is to connect struts and hibernate to make them better, in itself a hodgepodge of existing framework technologies.

2 spring Features (advantages)

    • Non-intrusive: refers to the Spring Framework API that does not appear on the business logic
    • Containers: Spring provides container functionality, uses containers to manage the life cycle of objects, and the dependencies between objects and objects.
    • IOC: Inversion of control, that is, the transfer of dependency, if it was previously dependent on implementation, then now the inverse to rely on abstraction, the core idea is to interface-oriented programming.
    • Dependency Injection: An implementation of dependency between objects and objects, including interface injection, construction injection, and set method injection. Only the latter two are supported in spring.
    • Aop: Aspect-oriented programming, the log, security, transaction management and other services (functions) understood as a "slice", formerly these services are usually directly written in the code of Business logic, it has two drawbacks: first, the business logic is not pure, followed by a lot of business logic is used repeatedly, can not be reused. AOP solves these problems by stripping out these services to form a "slice" that can be reused, and then dynamically inserting "slices" into business logic, making it easier for business logic to use the services provided by "facets."

There are other features such as support for frameworks, encapsulation and simplification of JDBC, provision of transaction management functions, encapsulation of jndi, mail and other services.

3 Spring Frame composition

As a whole, these modules give you everything you need to develop an enterprise application. But you don't have to apply it entirely based on the spring framework. You are free to choose the modules that are right for your application and ignore the rest of the modules.

As you can see, all the spring modules are built on top of the core container. The container defines how the bean is created, configured, and managed--more spring details. When you configure your app, you will potentially use these classes. But as a developer, you are most likely interested in other modules that affect the services provided by the container. These modules will provide you with frameworks for building application services, such as AOP and persistence.

Core container

This is the most basic part of the spring framework, which provides a dependency injection (dependencyinjection) feature to implement container-to-bean management. The most basic concept here is beanfactory, which is the core of any spring application. Beanfactory is an implementation of the factory pattern, which uses IOC to isolate application configuration and dependency descriptions from the actual application code.

Application Context ( Context ) Module

The beanfactory of the core module makes spring a container, and the context module makes it a framework. This module extends the concept of beanfactory and adds support for internationalization (i18n) messaging, event propagation, and validation.

In addition, this module provides many enterprise services, such as e-mail, jndi access, EJB integration, remote, and timing scheduling (scheduling) services. It also includes support for template frameworks such as velocity and freemarker integration.

    

Spring of the AOP Module

Spring provides rich support for slicing-oriented programming in its AOP modules. This module is the basis for implementing slice programming in spring applications. To ensure the interoperability of spring with other AOP frameworks, Spring's AOP supports APIs based on the AOP Alliance definition. An AOP consortium is an open source project whose goal is to promote the use of AOP and the interoperability of different AOP implementations by defining a common set of interfaces and components. By visiting their site, you can find out more about the AOP Alliance.

Spring's AOP module also introduces metadata programming to spring. With spring's metadata support, you can add comments to your source code, indicate where spring is and how to apply a tangent function.

JDBC Abstraction and DAO Module

Using JDBC often results in a lot of duplicate code, getting a connection, creating a statement, processing a result set, and then closing the connection. Spring's JDBC and DAO modules extract these duplicated code, so you can keep your database access code clean and concise, and prevent problems caused by the failure to shut down the database resources.

This module also establishes a meaningful anomaly layer on top of the error messages given by several database servers. So you no longer have to try to decipher the mysterious private SQL error message!

In addition, the module uses spring's AOP module to provide transaction management services for objects in spring applications.

Object / Relational Mapping Integration module

For those who prefer to use the object/relational mapping tool instead of using JDBC directly, Spring provides an ORM module. Instead of trying to implement its own ORM solution, Spring provides integration scenarios for several popular ORM frameworks, including Hibernate, JDO, and Ibatis SQL mappings. Spring's transaction management supports each of these ORM frameworks, including JDBC.

Spring of the Web Module

The Web context module is built on the application context module and provides a context appropriate for the Web application. In addition, this module provides some service-oriented support. For example: Multipart request for file upload, which also provides the integration of spring and other web frameworks, such as struts, webwork.

Spring of the MVC Frame

Spring provides a full-featured MVC framework for building Web applications. Although spring can be easily integrated with other MVC frameworks, such as struts, the Spring MVC Framework uses IOC to provide a complete separation of control logic and business objects.

It also allows you to declaratively bind request parameters to your business objects, and spring's MVC framework can take advantage of any other services in spring, such as internationalized information and validation.

4 concept of the IOC and DI

4.1 Ioc--inversion of Control inversion

IOC is the core concept of spring, and control inversion is that the application itself is not responsible for the creation and maintenance of dependent objects, and the creation and maintenance of dependent objects is the responsibility of the external container. Thus control is transferred from the application to the external container, and the transfer of control is called reversal.

When a Java instance (caller) needs another Java instance (callee), in the traditional programming process, there is usually a caller to create an instance of the callee, while control inversion transfers control, transferring the creation of the caller to the outer container (Spring container).

Simple implementation of the control reversal case:

//Userdao Public InterfaceUserdao { Public voidgetUser ();}//Userdaoimpl Public classUserdaoimplImplementsUserdao {@Override Public voidGetUser () {System.out.println ("Get user Dates"); }    }//UserService Public InterfaceUserService { Public voidgetUser ();}//Userserviceimpl Public classUserserviceimplImplementsUserService {PrivateUserdao Userdao;  Public voidSetuserdao (Userdao Userdao) { This. Userdao =Userdao; } @Override Public voidGetUser () {userdao.getuser (); }}//Test Public classTest { Public Static voidMain (string[] args) {Userserviceimpl userservice=NewUserserviceimpl (); Userservice.setuserdao (NewUserdaooracleimpl ());    Userservice.getuser (); }}

The object is created by the original program and becomes the receiving object of the program;

The programmer's main focus is on business implementation;

The service layer and the DAO layer are decoupled, there is no direct dependency, and if the DAO layer implementation changes, the application itself does not need to change.

4.2 Dependency Injection(Dependency injection)

IOC is also a design pattern, with dependency injection (dependency injection) and service Locator (service locator) implementations, and the spring framework uses dependency injection to implement IOC.

Dependency injection is the runtime in which dependent objects are dynamically injected into the component by an external container. That is, by using the spring framework, developers will not have to maintain dependencies between objects in their own code, simply by setting them in the configuration file, and spring automatically maintains dependencies between objects based on configuration information.

5 IOC container

5.1 IOC Container Overview

Spring's IOC container implements inversion of control, that is, during development, developers do not need to care about what the container is, nor do they need to invoke any API from the container. The container automates the initialization of managed objects and the maintenance of dependency between objects.

In spring, the most important is two packages that provide the basic functions of the IOC container

    • Org.springframework.beans
    • Org.springframework.context

How the 5.2 IOC container works

Org.springframework.beans.factory.BeanFactory is a spring container (also called spring
The actual representative of the IOC container, Beanfactory is the core interface of the IOC container. Its responsibilities include instantiating, locating, configuring objects in the application, and establishing dependencies between those objects. The entire IOC container is a large factory that provides beans to the application.

As you can see, we can configure the information needed in the application in the Spring IoC container, such as the Pojo object, the dependencies between these objects (beans), and the final output of the object for use.

5.3 Beanfactory interface and common implementation class xmlbeanfactory

The Beanfactory interface provides multiple implementation classes for developers to use, The most common use is the Org.springframework.beans.factory.xml.XmlBeanFactory class, which is a file in XML format that configures the Bean object to maintain relationships between objects.

When using an XML-formatted configuration file, the top-most layer of the configuration file is the <beans> element, which contains one or more <bean/> elements, each of which <bean/> element defines the instantiation information of a bean and its relationship to other beans.

Several basic methods in the Beanfactory interface:

    • Booleancontainsbean (String name)

Determine if the spring container contains a bean instance with ID name

    • Class GetType (String name)

Returns the type of the specified bean instance in the container

    • Objectgetbean (String name)

Returns the bean instance registered with the given name. Depending on the configuration of the bean, if the singleton mode returns a shared instance, a new instance will be returned. If the specified bean is not found, the method may throw an Beansexception exception (which will actually throw the nosuchbeandefinitionexception exception), and it may throw an exception when the bean is instantiated and preprocessed

Note: In the actual web application development, it is not necessary for the developer to initialize the container itself, and to generate the Beanfactory object, simply configure it in the. xml file.

5.4 ApplicationContext interface and common implementation class

Most of the time, we will not use the Beanfactory instance as the spring container, but instead use the ApplicationContext instance as the container, which is called the spring context. ApplicationContext is a beanfactory sub-interface that enhances the functionality of Beanfactory.

    • Common implementation classes for APPLICATIONCONTEXT interfaces:

Classpathxmlapplicationcontext: Loads context definition information from an XML file in the Classpath, and treats the context definition file as a classpath file, for example:

ApplicationContext context=newclasspathxmlapplicationcontext ("Beans-config.xml");

    • Filesystemxmlapplicationcontext: Loading context information from an XML file in the file system, for example:

ApplicationContext context=new filesystemxmlapplicationcontext ("D:/sp/beans-config.xml");

Difference: Filesystemxmlapplicationcontext can only find files in the specified path Beans-config.xml;classpathxmlapplicationcontext can be found throughout the classpath.

    • Xmlwebapplicationcontext: Loading context definition information from an XML file in the Web system

The difference between 5.5 beanfactory and ApplicationContext

ApplicationContext and beanfactory are spring containers that have responsibilities for instantiating, locating, configuring objects in the application, and establishing dependencies between these objects, but ApplicationContext provides more features:

    • ApplicationContext inherits the Messageresource interface and therefore provides international support.
    • Resource access, such as URLs and files.
    • Event mechanism to send an event to a bean registered as a listener.
    • Load multiple configuration files.
    • Start and create the spring container in a declarative manner.

6 How the Spring framework is introduced in the project

Resources download

    • Download Package official website https://spring.io/
    • Cloud Disk 4.1.6 version http://pan.baidu.com/s/1dEZ444h

6.1 Hello Spring

6.1.1 Importing related jar packages

Spring-aop-4.1.6.release.jar

Spring-aspects-4.1.6.release.jar

Spring-beans-4.1.6.release.jar

Spring-context-4.1.6.release.jar

Spring-context-support-4.1.6.release.jar

Spring-core-4.1.6.release.jar

Spring-expression-4.1.6.release.jar

Spring-jdbc-4.1.6.release.jar

Spring-orm-4.1.6.release.jar

Spring-tx-4.1.6.release.jar

Spring-web-4.1.6.release.jar

Spring-webmvc-4.1.6.release.jar

Commons-logging-1.1.3.jar (in struts software package)

6.1.2hellospring.java

 Public class hellospring {    private  String name;      Public void setName (String name) {        this. Name = name;    }       Public void Show () {        System.out.println ("Hello:" +name);}    }

6.1.3 Beans.xml

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns:p= "http://www.springframework.org/schema/p"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >   <Beanname= "Hello"class= "Com.silvan.pojo.HelloSpring">           < Propertyname= "Name"value= "Spring"></ Property>   </Bean></Beans>

6.1.4 Test.java

 Public class Test {    publicstaticvoid  main (string[] args) {        new Classpathxmlapplicationcontext ("Beans.xml");         = (hellospring) context.getbean ("Hello");        Hello.show ();    }}

Thinking:

Who created the Hellospring object? Spring container

Hellospring Object Properties who set the, how to set? The spring container, which is matched by the name of the property tag name after the set method.

This process is called inversion of control.

Summary: The previous object was created by the program itself, and after using spring, the program becomes passively accepting spring-created objects.

Control reversal There is another argument------dependency Injection

The result is that the initiative to do things become passive reception.

What's the difference between active and passive: the process is more automated and easier.

A detailed explanation of the IOC: http://www.cnblogs.com/xdp-gacl/p/3707631.html

Spring Introduction and IOC

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.