Spring (1), Spring (

Source: Internet
Author: User

Spring (1), Spring (

1.1 Spring framework Overview

 

1.1.1 what is Spring

  • Spring is an all-in-one lightweight open-source framework of hierarchical JavaSE and JavaEES.
    • Layering:
      • The three-tier structure of the EE provided by SUN: web layer, business layer, and data access layer (persistence layer and integration layer ).
      • Struts2 is a web layer based MVC design pattern framework.
      • Hibernate is An ORM framework of the persistence layer.
    • All-in-One:
      • The Spring framework has three layers of solutions:
      • Web layer: Spring MVC.
      • Persistent layer: JDBC Template.
      • Business Layer: Bean Management of Spring.

 

1.1.2Spring Core

  • IOC (Inverse of control): control inversion.
    • Control reversal: Assign the object creation permission to Spring for management.
    • IOC principle:

  • AOP (Aspect Oriented Programming): For Aspect-Oriented Programming.
    • Object-Oriented Programming: it is an extension of object-oriented functions. Instead of replacing object-oriented programming, it is used to solve some object-oriented problems.

 

Version 1.1.3Spring

  • Spring3.x and Spring4.x. Spring4.x must be integrated with Hibernate4.x.

 

1.1.4EJB: enterprise-level JavaBean

  • EJB: the EE solution proposed by SUN.

 

1.1.5Spring advantages

  • Convenient decoupling and simplified development
    • Spring is a large factory that allows you to create all objects and maintain dependency between them. It is managed by Spring.
  • Support for AOP Programming
    • Spring provides Aspect-Oriented Programming, allowing you to easily intercept permissions and monitor programs.
  • Support for declarative transactions
    • You only need to configure the transaction management, without manual programming.
  • Convenient program testing
    • Spring supports Junit4 and can easily test Spring programs through annotations.
  • Easy integration of various excellent frameworks
    • Spring does not exclude all kinds of excellent open-source frameworks. It provides direct support for various excellent frameworks (such as Struts2, Hibernate, MyBatis, and Quartz.
  • Reduces the difficulty of using Java EE APIs
    • Spring provides encapsulation For APIs (JDBC, JavaMail, and remote calls) that are difficult to use during Java EE development, greatly reducing the difficulty of these Apis.

 

1.2 getting started with Spring        

1.2.1Spring Architecture

  • The Spring framework is a layered architecture that contains a series of functional elements and is divided into about 20 modules. These modules are divided into Core iner, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and testing.

 

1.2.2 download Spring Development Kit

  • Spring-framework-3.2.0.RELEASE-dist.zip-Spring Development Kit
    • Docs: APIs and specifications of the Spring framework.
    • Libs: jar package developed by Spring.
    • Schema: Constraints of XML.
  • Spring-framework-3.0.2.RELEASE-dependencies.zip -- Dependency packages in Spring development

 

1.2.3 create a web project and introduce the corresponding jar package.

  • Core Container:
    • Spring-beans-3.2.0.RELEASE.jar
    • Spring-core-3.2.0.RELEASE.jar
    • Spring-context-3.2.0.RELEASE.jar
    • Spring-expression-3.2.0.RELEASE.jar
  • The jar package for logging:
    • Com.springsource.org. apache. commons. The jar package that the logging-1.1.1.jar uses to integrate other logs (similar to slf4j in Hibernate)
    • Com.springsource.org. apache. log4j-1.2.15.jar

 

1.2.4 create a Spring configuration file

  • Create an applicationContext. xml file under src
  • Introduce XML constraints:
<?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">    </beans>

 

1.2.5 introduce log4j. properties

### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.errlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file mylog.log ###log4j.appender.file=org.apache.log4j.FileAppenderlog4j.appender.file.File=c\:mylog.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=info, stdout

 

1.2.6 experience traditional development and Spring development

  • Create an interface: HelloService. java.
Package cn. spring3.demo1;/*** getting started case */public interface HelloService {public void sayHello ();}
  • Create an implementation class: HelloServiceImpl. java.
package cn.spring3.demo1;public class HelloServiceImpl implements HelloService {    @Override    public void sayHello() {        System.out.println("Hello Spring");    }        }
  • Traditional development-Polymorphism
@ Test // traditionally public void demo1 () {HelloService helloService = new HelloServiceImpl (); helloService. sayHello ();}
  • Spring Development
    • Configure the <bean> label in the applicationContext. xml file.
      • <! --
        You can use the <bean> label to set the class information and use the id attribute to identify the class.
        -->
        <Bean id = "helloServiceImpl" class = "cn. spring3.demo1. HelloServiceImpl"/>

    • The applicationContext. xml file contains the following content:
<? 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"> <! -- Use the <bean> label to set the class information and use the id attribute to set an identifier for the class --> <bean id = "helloServiceImpl" class = "cn. spring3.demo1. helloServiceImpl "/> </beans>
    • Test code
@ Test // Spring development public void demo2 () {// create a factory class ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("applicationContext. xml "); HelloService helloService = (HelloService) applicationContext. getBean ("helloServiceImpl"); helloService. sayHello ();}

 

1.2.7what is the difference between IOC and DI?

  • IOC: controls the inversion, and submits the object creation permission to Spring for management.
  • DI: dependency injection. When creating an object in Spring, it injects the object attributes into the class.
    • Relationship between objects in object orientation
      • Dependency:
public class A{      private B b;              }
      • Inheritance: is.
      • Aggregation:
        • Aggregation
        • Combination
    • Example:
      • HelloService. java class
Package cn. spring3.demo1;/*** getting started case */public interface HelloService {public void sayHello ();}
      • HelloServiceImpl. java class
package cn.spring3.demo1;public class HelloServiceImpl implements HelloService {    private String info;            public String getInfo() {        return info;    }    public void setInfo(String info) {        this.info = info;    }    @Override    public void sayHello() {        System.out.println("Hello"+info);    }        }
      • 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"> <! -- Use the <bean> label to set the class information and use the id attribute to start an identifier for the class --> <bean id = "helloServiceImpl" class = "cn. spring3.demo1. HelloServiceImpl"> <! -- Use <property> label injection property --> <property name = "info" value = "Spring"> </property> </bean> </beans>
      • Test code
@ Test // Spring development public void demo2 () {// create a factory class ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("applicationContext. xml "); HelloService helloService = (HelloService) applicationContext. getBean ("helloServiceImpl"); helloService. sayHello ();}

 

1.2.8Spring framework load configuration file

  • ApplicationContext: loads the Spring framework configuration file.
    • Load classpath:
      • New ClassPathXmlApplicationContext ("applicationContext. xml"); load the configuration file under classpath.
    • Disk loading path:
      • New FileSystemXmlApplicationContext ("applicationContext. xml");: load the configuration file on the disk.

 

 

What is the difference between 1.2.9BeanFactory and ApplicationContext?

 

  • The ApplicationContext class inherits BeanFactory.
  • When BeanFactory is using this class, the getBean () method will be loaded to this class. (Delayed loading ).
  • All classes are created when the ApplicationContext class loads the configuration file.
  • ApplicationContext provides extended functions for BeanFactory.
    • International processing.
    • Event transfer.
    • Automatic Bean assembly.
    • Context implementation for different application layers.
  • * *** BeanFactory was used for early development.

 

1.2.10MyEclipse configuration XML prompt

  • Copy the Schema Location.

  • Windows -- preferences -- XML Catalog

                  

1.3 IOC Assembly Bean    

1.3.1Spring framework Bean instance method:

  • Three Bean instantiation methods are provided.
    • Constructor instantiation: (No parameter by default) -- Reflection
      • <Bean id = "helloServiceImpl" class = "cn. spring3.demo1. HelloServiceImpl"/>
Package cn. spring3.demo2;/*** use the parameter-free method to instantiate */public class Bean1 {}
<bean id="bean1" class="cn.spring3.demo2.Bean1"></bean>
@ Test // The constructor without parameters instantiate public void demo1 () {ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("applicationContext. xml "); Bean1 bean1 = (Bean1) applicationContext. getBean ("bean1"); System. out. println (bean1 );}
    • Static factory method instantiation (simple factory mode) -- Reflection + simple factory
Package cn. spring3.demo2;/*** use static factory instantiation */public class Bean2 {}
Package cn. spring3.demo2;/*** Bean2 static factory */public class Bean2Factory {public static Bean2 getBean2Instance () {return new Bean2 ();}}
<bean id="bean2Factory" class="cn.spring3.demo2.Bean2Factory" factory-method="getBean2Instance" ></bean>
@ Test // instantiate public void demo2 () {ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("applicationContext. xml "); Bean2 bean2 = (Bean2) applicationContext. getBean ("bean2Factory"); System. out. println (bean2 );}
    • Instance factory instantiation (Factory method mode) --- reflection + instance Factory
Package cn. spring3.demo2;/*** use instance factory */public class Bean3Factory {public Bean3 getBean3Instance () {return new Bean3 ();}}
Package cn. spring3.demo2;/*** use instance factory instantiation */public class Bean3 {}
<! -- Used to initialize Bean3Factory --> <bean id = "bean3Factory" class = "cn. spring3.demo2. bean3Factory "> </bean> <bean id =" bean3 "factory-bean =" bean3Factory "factory-method =" getBean3Instance "> </bean>
@ Test // use the instance factory to instantiate public void demo3 () {ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("applicationContext. xml "); Bean3 bean3 = (Bean3) applicationContext. getBean ("bean3"); System. out. println (bean3 );}
  • Analysis:
    • Constructor instantiation: (No parameter by default) -- Reflection
      • Directly give Spring a complete Class Name, Spring will help us instantiate the object.
    • Static factory method instantiation (simple factory Mode)
      • To give a factory-method, because the static method can be directly passed through the class name. method () to call the method, and class = "", of course, is the class name of the static factory, because only in this way can Spring help us initialize the factory and return the required instantiated object.
    • Instance factory instantiation (Factory method mode)
      • Because the instance factory is not a static factory, you cannot use the class name. method (), so you must first let Spring instantiate the instance factory, and then tell the Spring instance factory what the object name is and what method to instantiate the object.

 

Other configurations of 1.3.2Bean 

    • Difference between id and name
      • Id is subject to the id constraint of the XML constraint. The id constraint ensures that the value of this attribute is unique and must start with a letter. You can use letters, numbers, hyphens, periods, and colons.
      • Name does not have these requirements
        • If no id is configured on the bean tag, the name can be used as the id.
      • In early development, Spring integrated Struts1, "/login" is a special character and can only use name.
        • <Bean name = "/login"/>
      • You can use the id attribute in current development.

 

 

  • CATEGORY scope:
    • Scope attributes:
      • Singleton: singleton. (Default)
      • Prototype: Multiple instances.
      • Request: used in web development. Create an object and store it in the request range, request. setAttribute ().
      • Session: used in web development. Create an object and store it in the session range, session. setAttribute ().
      • GlobalSession: generally used in the Porlet application environment, which refers to distributed development. Not a Porlet environment, globalSession is equivalent to session.
    • Singleton and prototype are mainly used in actual development.

 

  • Bean Lifecycle
    • How to configure Bean initialization and destruction
      • Init-method = "setUp ".
      • Destory-method = "teardown ".
    • When executing the destruction, you must manually link the factory, and the detachment scope = "singleton" is valid.

 

    • Example:
      • Product. java
Package cn. spring3.demo3; public class Product {// initialization method public void setup () {System. out. println ("Initialization Method");} // destroy method public void teardown () {System. out. println ("destruction method ");}}
      • ApplicationContext. xml
<bean id="product" class="cn.spring3.demo3.Product" init-method="setup" destroy-method="teardown"/>
      • Test code:
@ Test // Test the initialization and destruction method public void demo1 () {ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext ("applicationContext. xml "); Product product = (Product) applicationContext. getBean ("product"); applicationContext. close ();}
    • 11 steps of Bean lifecycle:

 

 

 

 

 

 

 

 

 

    

    

    

       

 

 

 

 

 

           

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.