Spring Frame Notes

Source: Internet
Author: User
Tags aop constructor getmessage http request lowercase valid xmlns

Spring Introduction

Spring is an open source framework that has been created to address the complexities of enterprise application development, but has now been applied not only to enterprise applications, but to a lightweight control inversion (IOC) and facet-oriented (AOP) container framework.

Spring is a lightweight framework relative to the Java official Heavyweight framework EJB, and it takes only a simple Java class to complete and spring open source.
Spring's support for mainstream Java technology (persistent layer hibernate, JDBC, MyBatis) can also be seen as a composite of Java applications.
Spring main application Scenarios:
Ssh:structs (MVC Classic) +hibernate (representative of Persistence layer Technology) +spring (managing the entire project)

Advantages of Spring :
1. Decoupling

In the past, service layer was coupled with DAO layer, when DAO beginning wrong, service also error, Service layer and DAO layer were seriously coupled
The goal of loose coupling is achieved through the technique of inversion of control (IOC).

Support for 2.AOP programming
3. Declarative transactional support
4. Convenient program Testing
5. Easy to inherit various excellent frameworks
6. Reduce the difficulty of using Java EE
7.Spring source code can be used as a learning paradigm

Spring 4 Chinese Reference Document: https://github.com/b2gats/stone-docs/blob/master/spring-4-beans.md# Beans-factory-properties-detailed 1 Interface Programming structure design, distinguish between hierarchy and call relationship, each layer only outward (upper) to provide a set of functional interfaces, each layer depends only on the interface rather than the implementation class Changes in interface implementations do not affect calls between tiers, which is particularly important in public services "interfaces" in "interface-oriented programming" are components for hiding concrete implementations and implementing polymorphism

Public interface Oninterface {public
    string Hello (string word);
}
public class Oninterfaceiml implements Oninterface {

    @Override public
    string Hello (string word) {
        return] HEllo World "+word;
    }

}
public class Testmain {public
    static void Main (string[] args) {
        oninterface oif = new Oninterfaceiml ();
        The object that implements the interface class is assigned a reference to the interface
        System.out.println (Oif.hello ("Peng"));}
}
2 IOC

Object creation Unified hosting
Specification Lifecycle Management
Flexible Dependency Injection
consistent fetch objects

The creation and destruction of all classes are controlled by spring, that is, the object's lifetime is no longer the object that references it, but spring; for a specific object, it used to control other objects, and now all objects are controlled by spring, so this is the reversal.
The IOC essence is to discard the new method to obtain the object, through the configuration to obtain the object.
the theoretical background of the IOC:

When object a runs to object B, the IOC container actively creates an object B to inject into object a where it is needed. Object A gets the behavior of object B from active to passive behavior.

In the spring configuration file, the following configuration

<bean id= "Date" class= "Java.util.Date" ></bean>

Equivalent:

Date date = new Date (); And date is a singleton.

IOC popular example understanding

Requirement: Now a girl wants to find a boyfriend

Girl->?-> Boyfriend

A. Find out for yourself

public void Getboyfriend () {Boys
    = new Boy ();//Create a boyfriend object for yourself
}

B. Through intermediaries (intermediaries are used to obtain related services)
Boyfactory the corresponding method:

Public Boy Getboy () {
    return to New Boy ();
}

The Girl class corresponds to the method:

public void Getboyfriend () {Boy
    = Boyfactory.getboy ();
}

C. Parent-arranged
After the girl reaches the age, the boyfriend automatically appears in front (spring abstract understanding)

Private boy boy;//needs to have injected code to implement public
void Getboyfriend () {
    this.boy;//an object passed in from outside
}

IOC injection

3 Beans

In the IOC, all objects are called beans

After using IOC

naming rules

The name of the ID is made up of numbers, letters, and $ (the first letter cannot be a number)
Java attributes are named in addition to the above naming conventions, but also note that

First letter lowercase, the first letter of the next word capitalized
If the first word has only one letter, the first letter of the second word is also lowercase

<bean id= "Userdao" class= "Com.peng.dao.impl.UserDAOImpl" scope= "session" ></bean>

<bean id= " Userdao "class=" Com.peng.dao.impl.UserDAOImpl "scope=" prototype "></bean>

<bean id=" Userdao "class= "Com.peng.dao.impl.UserDAOImpl" scope= "Singleton" ></bean>
Scope Description
Singleton (default singleton) A bean definition corresponds to an object instance in each spring IOC container.
Prototype (prototype) A bean definition corresponds to multiple object instances.
Request In an HTTP request, a bean definition corresponds to an instance, that is, each HTTP request will have its own bean instance, which is created from a bean definition. This scope is valid only in the case of a web-based spring ApplicationContext.
Session In an HTTP Session, a bean definition corresponds to an instance. This scope is valid only in the case of web-based Springapplicationcontext
Global session In a global HTTP Session, a bean definition corresponds to an instance. Typically, this is only valid when using the Portlet context. This scope is valid only in the case of a web-based spring ApplicationContext.

In the singleton, each spring IOC container has only one instance, and it always returns the same instance, no matter how many times it calls the Getbean () method to get it.

CustomerService Custa = (customerservice) context.getbean ("CustomerService");
Custa.setmessage ("Message by Custa");
System.out.println ("Message:" + custa.getmessage ());

Retrieve it again
customerservice custb = (customerservice) context.getbean ("CustomerService");
System.out.println ("Message:" + custb.getmessage ());

Two times the result is the first time the result is set.

Message:message by Custa

In prototype mode, the result is the following

Message:message by Custa
Message:null
Spring Auto Load Bean

The so-called automatic assembly is the injection of a bean into the property of another bean, similar to the following:

<bean id= "Customer" class= "Com.lei.common.Customer" autowire= "ByName"/>

Spring supports 5 automatic assembly modes, as follows:

type Description
No By default, it is not automatically assembled and manually set by the "ref" attribute.
Buname Automatic assembly according to the name of the property, if the name of a bean is the same as the name of the property in another bean, the bean is automatically assembled into the property.
Bytype Automatically assembled according to the property's data type (type), if one bean's data type is compatible with the data type of the property in another bean, it is automatically assembled.
Constructor According to the data type of the constructor parameter, the automatic assembly of Bytype mode is carried out.
AutoDetect If the default constructor is found, use constructor mode, otherwise, use Bytype mode.

Example http://www.yiibai.com/spring/spring-auto-wiring-beans-in-xml.html

Test

Customer.java

Package Com.peng.dao.impl;

public class Customer {
    private person person = null;

    public void Setperson (person person) {
        This.person = person;
    }

    public void First () {
        System.out.println ("I am the customer, gets the content of the person method" +person.getmsg ());}
}

Person.java

Package Com.peng.dao.impl;

public class Person {public

    String getmsg () {
        return "I am a message in person";
    }
}

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"
     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 ">


        <bean id=" Userdao "class=" Com.peng.dao.impl.UserDAOImpl "></bean >    
        <bean id= "Customer" class= "Com.peng.dao.impl.Customer" autowire= "byname" >

        </bean>
        <bean id= "Person" class= "Com.peng.dao.impl.Person" ></bean>
 </beans>

Test.java

Package test;

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

Import Com.peng.dao.UserDAO;
Import Com.peng.dao.impl.Customer;

public class Test {public

    void Testautowrie () {
        ApplicationContext context = new 
                Classpathxmlapplicationcontext ("Classpath:applicationContext.xml");
        Customer C = Context.getbean ("Customer", customer.class);
        C.first ();
    }
    public static void Main (string[] args) {
        test test = new test ();
        Test.testautowrie ();
    }
}   
I am the customer, get the content of the person method I am the message in person
4 JUnit Test

6 AOP face tangent

In the software industry, AOP is the abbreviation for Aspect oriented programming, which means: face-cutting programming, through the pre-compilation method and runtime dynamic agent to implement the unified maintenance of the program functions of a technology. AOP is a continuation of OOP, a hotspot in software development, an important content in the spring framework, and a derivative model of functional programming. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development.

Configuring the Spring environment Spring jar package Download Address

http://repo.spring.io/release/org/springframework/spring/

Spring Tool Suite

Spring Tool Suite Download Address:

Http://spring.io/tools/sts/all

The eclipse version is 4.6.0, the STS cannot be downloaded through Eclipse Marketplace, the installation will fail, and installing the 4.5 update sites via the install new software will succeed, but the new spring Projec T, there is no spring project, there is Spring starter project, and so on.

Download the latest version of the 4.6.1 version of Eclipse can be used with the 4.61 version of the


Above the zip package, there are STS offline package and update Site Archives, also only springsource ... Can be installed at install new software, which is the package under download update Site archives

The package downloaded below cannot be downloaded offline, and the reason is not found
Build a Java project Test spring

Course Study Address: http://www.chuanke.com/v7232853-198066-1144815.html

Here the JUnit package is not available, commons-logging package can be found in the structs package, no this package will be error.

Userdao.java

Package Com.peng.dao;

Public interface Userdao {public
    void SayHello ();
}

Userdaoimpl.java

Package Com.peng.dao.impl;

Import Com.peng.dao.UserDAO;

public class Userdaoimpl implements Userdao {

    @Override public
    void SayHello () {
        System.out.println ("Hello World! ");
    }   
}

Applicationcontext.xml

The XML file name can be arbitrarily

<?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 ">
        <bean id= "Userdao" class= "Com.peng.dao.impl.UserDAOImpl" ></bean>
 </beans>

Test.java

Package test;

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;

Import Com.peng.dao.UserDAO;

public class Test {
    /**
     * 1. Read the spring container
     * 2. Find the object we need from the spring container *
     3. Call the required method from the resulting object
     * @param args< c9/>*/public
    void Dofirst () {
        //1. Read Spring container
        applicationcontext context = new 
                Classpathxmlapplicationcontext ("Applicationcontext.xml");
        2. Find the object we need from the Spring container
        Userdao dao = Context.getbean ("Userdao", userdao.class);
        Only the interface needs to be called, regardless of its implementation
        Dao.sayhello ();

    }
    public static void Main (string[] args) {
        test test = new test ();
        Test.dofirst ();
    }
}   

Operation Result:

November 09, 2016 8:56:20 pm org.springframework.context.support.AbstractApplicationContext preparerefresh
Info: refreshing org.springframework.context.support.classpathxmlapplicationcontext@7eda2dbb:startup Date [Wed Nov 09 20:56:20 CST 2016]; Root of the context hierarchy
November 09, 2016 8:56:20 pm Org.springframework.beans.factory.xml.XmlBeanDefinitionReader Loadbeandefinitions
Info: Loading XML Bean Definitions from class path resource [Applicationcontext.xml]
Hello world!
1 using JUnit to test spring

Userdao.java

Package Com.peng.dao;

Public interface Userdao {public
    void SayHello ();
}

Userdaoimpl.java

Package Com.peng.dao.impl;

Import Com.peng.dao.UserDAO;

public class Userdaoimpl implements Userdao {

    @Override public
    void SayHello () {
        System.out.println ("Hello World! ");
    }   
}

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 ">
        <bean id= "Userdao" class= "Com.peng.dao.impl.UserDAOImpl" ></bean>
 </beans>

Testuserdao.java

//package Junit.com.peng.dao;
Import Org.junit.Test;
Import Org.junit.runner.RunWith;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext; 

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.