Spring Study Notes (1)

Source: Internet
Author: User

1. Spring development steps
1.1 create a Java or JavaEE Project
1.2 import related jar packages
Org. springframework. asm-3.1.1.RELEASE.jar -- word code processing

Org. springframework. core-3.1.1.RELEASE.jar -- spring core, access resources

Org. springframework. beans-3.1.1.RELEASE.jar -- core container

Org. springframework. context-3.1.1.RELEASE.jarApplicationContext and other classes in this package

Org. springframework. expression-3.1.1.RELEASE.jarSpring3 EL

Commons-logging.jar --- the only third party that spring must depend on, log

1.3 create a test class
Peron class:

Publicclass Person {

Private Integer id;

Private String name;

Private Integer age;

Private Address address;

}

Address class:

Publicclass Address {

Private String province;

Private String city;

Private String area;

}

Configuration File beans. xml:

<? Xml version = "1.0" encoding = "UTF-8"?>

<! -- The document states that the configuration file of spring 3 is constrained by schema -->

<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-3.0.xsd>

<Bean id = "address" class = "com. maple. spring. helloworld. Address">

<Property name = "province" value = "Guangdong province"/>

<Property name = "city" value = "Guangzhou city"/>

<Property name = "area" value = "Haizhu District"/>

</Bean>

<! -- Creates an object using the null parameter constructor by default -->

<Bean id = "p" name = "p1" class = "com. maple. spring. helloworld. Person">

<Property name = "id" value = "1000" type = "parmname" text = "parmname"/>

<Property name = "name" value = "Zhang San"/>

<Property name = "age" value = "23"/>

<! -- Reference another bean -->

<Property name = "address" ref = "address"/>

</Bean>

<! -- Alias p -->

<Alias name = "p" alias = "p11"/>

<! -- Create an object using the parameter constructor -->

<Bean id = "p2" class = "com. maple. spring. helloworld. Person">

<! -- The order is best consistent with the parameter order in the constructor -->

<Constructor-arg value = "1000" type = "codeph" text = "codeph"/>

<Constructor-arg value = "James"/>

<Constructor-arg value = "23"/>

<Constructor-arg ref = "address"/>

</Bean>

</Beans>

2. Spring container details
2.1 container Overview
Features: not only provides the ability to store things, but also creates objects in containers, manages relationships among other functions, and peripheral functions (logs and security checks ).

Container development in Java: No container (JVM + programmer) = factory age ---> old EJB age, heavyweight container (JavaEE container, there are many restrictions on putting it into containers) /or a certain field (Web Container) --> the light container era (PicoContainer, Spring, Apache HiveMind, Guice, xWork) -- The New EJB era (there are not many restrictions on putting containers into it)

2.2 Inversion of Control, IOC)
Concept: an object on which a component depends is created and set to a component by an external container. Transferring the control of the dependent object from the component to the external (container) is called the control inversion IOC. Its core is dependency injection.

 

Public class Girl {

Private Boy boy = new Boy (); // object on which Girl is dependent

Public void kiss (){

System. out. println (boy. getBoyObject ());

}

}

Boy is created and maintained inside the application. The so-called control inversion means that the application itself is not responsible for the creation and maintenance of dependent objects, and the creation and maintenance of dependent objects are the responsibility of external containers. In this way, the control right is transferred from the application to the external container, and the control right is reversed to achieve better scalability and maintainability.

2.3 Dependency Injection)
Dependency injection refers to the Dynamic Injection of dependent objects into components by external containers during runtime.

Dependency injection: injects the dependent objects into a component in four ways.

A interface injects Type1 (obsolete)/Type2

Setter/Type3

C construct subinjection

D Field Injection)

1) Use setter injection:

 

2) use constructor injection:

 

3) use field injection:

 

Publicstaticvoid main (String [] args ){

ApplicationContextacx = new ClassPathXmlApplicationContext ("com/maple/spring/inject/beans. xml ");

// Personp1 = (Person) acx. getBean ("p1"); // setter

// P1.say ();

// Personp2 = (Person) acx. getBean ("p2"); // Constructor

// P2.say ();

Personp3 = (Person) acx. getBean ("p3"); // Field

P3.say ();

}

<? Xml version = "1.0" encoding = "UTF-8"?>

<Beans xmlns = "http://www.springframework.org/schema/beans"

Xmlns: context = "http://www.springframework.org/schema/context"

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-3.0.xsd

Http://www.springframework.org/schema/context

Http://www.springframework.org/schema/context/spring-context-3.0.xsd>

<! -- Use the setter Method for injection. The setter method must be provided for the property of the injected value. -->

<Bean id = "p1" class = "com. maple. spring. inject. Person">

<Property name = "id" value = "1000" type = "parmname" text = "parmname"/>

<Property name = "name" value = "Zhang San"/>

<Property name = "age" value = "22"/>

</Bean>

<! -- Create an object using the parameter constructor -->

<Bean id = "p2" class = "com. maple. spring. inject. Person">

<! -- The sequence is best consistent with the parameter sequence in the constructor. The index and type are used to specify the parameter location and type. -->

<Constructor-arg value = "2000" type = "codeph" text = "codeph"/>

<Constructor-arg value = ""/>

<Constructor-arg value = "23"/>

</Bean>

<! -- Use field injection -->

<Bean id = "p3" class = "com. maple. spring. inject. Person">

<Property name = "id" value = "1000" type = "parmname" text = "parmname"/>

<Property name = "name" value = "Zhang San"/>

</Bean>

<! -- Enable annotation scanning and use field injection -->

<Context: annotation-config/>

<! -- When field injection is used, in addition to adding the @ Autowired tag to the field, a bean of the matching type is also provided. Used to automatically set fields -->

<Bean id = "age1" class = "java. lang. Integer">

<Constructor-arg value = "24"/>

</Bean>

</Beans>

3. Spring container initialization process (different implementations have different processes)
A. register the Bean information (BeanDefinition) to the Bean factory based on the loaded configuration file information.

B. Check whether to initialize some beans based on the BeanDefinition object.

C. Process dependency injection (according to the dependency injection information in BeanDefinition)

D. The client queries service components through containers.

E. Destroy the container when it is closed.

4. Bean Factory and application context
1) BeanFactory -- the most basic container interface of Spring

2) ApplicationContext -- application-level container (provides methods for accessing Environment Resource Information)

 

ApplicationContext getParent () -- Concept of the container Layer Structure

ApplicationContext automatically loads the singleton Bean during initialization. BeanFactory is not loaded during initialization.

The application context ApplicationContext is a higher-level Spring IOC Container built on BeanFactory. It has all the functions of common BeanFactory, it also includes functions closely related to applications, such as resource access, event propagation, and automatic loading context.

Most J2EE applications directly use the application context file, such as the Web application, and generally do not use code in the program to load the application context, instead, the application context is automatically loaded when the application starts.

5. Three Bean instantiation Methods
5.1 using Constructors
By default, there is no parameter constructor. You can also use parameters.

(1) constructor without Parameters

PublicPerson (){

System. out. println ("initialize person ");

}

 

(2) configuration without Parameters

<! -- Use the default non-parameter constructor for initialization -->

<Beanid = "p1" class = "cn.itcasg.gz. springioc. Person"> </bean>

(3) constructor with Parameters

Public Person (String name ){

This. name = name;

System. out. println ("create Person, constructor 1 ");

}

(4) configuration with Parameters

<! -- Specify to use a constructor with a parameter to initialize the Bean -->

<Beanid = "p2" class = "cn.itcasg.gz. springioc. Person">

<Constructor-argvalue = "Zhang Wuji"> </constructor-arg>

</Bean>

5.2 use static factory methods
(1) factories without Parameters

Public class PersonFactory {

Publicstatic Person createPerson (){

System. out. println ("createPerson ()...");

Return new Person ();

}

}

(2) configuration without Parameters

<! -- Create a Person using the static factory method -->

<Bean id = "p3" class = "cn.itcasg.gz. springioc. PersonFactory" factory-method = "createPerson"> </bean>

 

 

(3) Factory method with Parameters

 

Public class PersonFactory {

Publicstatic Person createPerson (String name ){

System. out. println ("createPerson ()... 222222 ");

Returnnew Person (name );

}

}

(4) configuration with Parameters

<! -- Use the static factory method with parameters -->

<Beanid = "p4" class = "cn.itcasg.gz. springioc. PersonFactory" factory-method = "createPerson">

<Constructor-argvalue = "Yang Guo"> </constructor-arg>

</Bean>

5.3 use the dynamic factory Method
(1) Factory

Public class PersonFactoryFamily {

PrivateString family;

Publicvoid setFamily (String family ){

This. family = family;

}

Public Person createPerson (){

System. out. println ("createPerson ()...");

Returnnew Person (family + ":");

}

Public Person createPerson (String name ){

System. out. println ("createPerson ()... 2 ");

Returnnew Person (family + ":" + name );

}

}

(2) Configuration

<! -- Create a Person using the dynamic factory method -->

<! -- First define the factory Beanclass value as the full Class Name of the factory class -->

<Beanid = "wangFactory" class = "cn.itcasg.gz. springioc. PersonFactoryFamily">

<Propertyname = "family" value = "Wang"/>

</Bean>

<Beanid = "p5" factory-bean = "wangFactory" (specify the factory class to use)

Factory-method = "createPerson" (specifies the method that calls the factory class)>

<Constructor-argvalue = ""/> </bean>

<Beanid = "p6" factory-bean = "wangFactory" factory-method = "createPerson"/>

6. Bean scope (survival)
1) singleton (default)

In each Spring IoC container, a bean defines only one object instance (SHARE ).

By default, the bean is initialized when the container is started, but we can specify the Bean node's lazy-init = "true" to delay bean initialization. At this time, the bean is initialized only when the bean is obtained for the first time. For example:

<Bean id = "xxx" class = "cn. itcast. OrderServiceBean" lazy-init = "true"/>

If you want to apply delayed initialization to all beans, you can set default-lazy-init = "true" in the root node beans, as shown below:

<Beans default-lazy-init = "true"...>

2) prototype allows beans to be instantiated multiple times (an instance is created once)

3) The request lifetime is valid for one request. It can only be used in WEB references. The lifecycle of the request object is the same as that of the request object on the web.

4) The session lifetime is valid for one session. Only valid for web applications. (Such as car purchase Bean)

5) The global session (the Portlet Specification defines the portlet as a "Java-based web component, managed by the portlet container that processes requests and generates dynamic content") is only valid in the Portlet environment application.

7. Assembly Method
7.1 Manual assembly
The following three methods are all manual assembly: see 2.3

Used labels or annotations <property>, <constructor-arg>, @ Autowired, and @ Resource.

1) Use setter injection:

2) use constructor injection:

3) use field injection:

7.2 automatic assembly (rarely used)
Autowire attribute to specify the automatic assembly type.

<Bean id = "p4" class = "com. maple. spring. inject. Person" autowire = "byName"/>

Value of the autowired attribute:

ByName: automatically assemble by name without assembling the basic type.

ByType: automatic assembly by type

Constructor: the constructor is automatically assembled based on the type of constructor parameters. The largest number of parameters is selected and the number of parameters is queried in turn.

 

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.