Spring Knowledge Point Refinement

Source: Internet
Author: User
Tags aop constructor error handling exception handling to domain
Spring Knowledge Point refinement 1. The role of the spring framework

Lightweight: Spring is lightweight, with a basic version size of 2MB

Control inversion: Spring is loosely coupled through control inversion, and objects are given their dependencies rather than creating or locating dependent objects.

Tangent-oriented programming aop:spring supports aspect-oriented programming and separates application business logic from system services.

Containers: Spring contains and manages the life cycle and configuration of objects in your app

MVC Framework: SPRING-MVC

Transaction management: Spring provides a continuous transaction management interface that can be extended up to the local transaction down to the global transaction JTA

Exception handling: Spring provides a handy API to put specific technology-related exceptions to 2. The composition of spring


Spring consists of 7 modules:

Spring Core: The core container provides the basic functionality of the spring framework. The main component of the core container is Beanfactory, which is the implementation of the factory pattern. The beanfactory uses the inversion of control (IOC) pattern to separate the application's configuration and dependency specifications from the actual application code.

Spring Context: The spring context is a configuration file that provides contextual information to the spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internationalization, checksum scheduling.

Spring AOP: With the configuration management feature, the Spring AOP module directly integrates aspect-oriented programming capabilities into the spring framework. Therefore, it is easy to enable any object managed by the Spring framework to support AOP. The spring AOP module provides transaction management services for objects in spring-based applications. By using Spring AOP, you can integrate declarative transaction management into your application without relying on EJB components.

The Spring dao:jdbc DAO Abstraction Layer provides a meaningful exception hierarchy that can be used to manage exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the number of exception codes that need to be written (such as opening and closing connections). Spring DAO's JDBC-oriented exception conforms to the common DAO exception hierarchy.

The Spring orm:spring Framework inserts several ORM frameworks, providing ORM object-relational tools, including JDO, Hibernate, and IBatis SQL Map. All of these conform to Spring's common transaction and DAO exception hierarchies.

Spring Web module: The Web context module is built on top of the application context module and provides the context for Web-based applications. Therefore, the Spring framework supports integration with Jakarta Struts. The Web module also simplifies the process of working with multipart requests and binding request parameters to domain objects.

Spring MVC framework: The MVC Framework is a full-featured MVC implementation of building WEB applications. With the policy interface, the MVC framework becomes highly configurable, and MVC accommodates a large number of view technologies, including JSP, Velocity, Tiles, IText, and POI. 3. Spring Container

The sping container can be divided into two types
1. Beanfactory: (Org.springframework.beans.factory.BeanFactory interface definition) is the simplest container that provides basic DI support. The most commonly used beanfactory implementation is the Xmlbeanfactory class, which loads beans from the XML file, reads the configuration metadata from the file and uses it to create a fully configured system or application.
2. ApplicationContext Application Context: (Org.springframework.context.ApplicationContext) built on top of Beanfactory and provides application-oriented services. 4. Common implementations of ApplicationContext

Classpathxmlapplicationcontext: Loads the context definition from the XML configuration file under the Classpath and uses the context definition file as the class resource.

Filesystemxmlapplicationcontext: Reads the XML configuration file under the file system and loads the context definition.

Xmlwebapplicationcontext: Reads the XML configuration file under the Web application and loads the context definition.

ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml");

5. IOC & DI

Inversion of Control is generally divided into two types: Dependency injection di (Dependency injection) and dependent lookup (Dependency Lookup). Dependency injection applications are extensive.

Spring IOC is responsible for creating objects, managing Objects (DI), assembling objects, configuring objects, and managing the entire life cycle of these objects.

Pros: Minimize the amount of code applied. Container testing, with minimal cost and minimal intrusion, makes loose coupling possible. The IOC container supports a hungry man initialization and lazy loading when the service is loaded.
Di Dependency injection is an aspect of the IOC and is a common concept, and it has many interpretations. The concept is that you don't use a bed frame object, but simply describe how it was created. You don't assemble your components and services directly in the code, but you want to describe what services the component needs in the configuration file, and then an IOC container assists in assembling them.
How the IOC is injected: 1. constructor dependency injection; 2. Setter method Injection. 6. How to provide configuration metadata to the spring container

XML configuration file

Annotation-based configuration

Java-based configuration @configuration, @Bean 7. Attributes in the Bean tag:

ID
name
class
Init-method: The method that will be called immediately after the Bean is instantiated
Destory-method: The method that is called before the bean is removed from the container and destroyed
Factory-method: Run We call a specified static method, instead of constructing a method to create an instance of a class.
Scope: The scope of the bean, including singleton (default), prototype (an instance is created for each call), Request,session, Global-session (note that the singleton bean in spring is not thread-safe)
autowired: Automatic Assembly ByName, Bytype, constructor, AutoDetect (first illustrates the use of constructor automatic assembly, if no bean matching the constructor is found, Spring will try to use Bytype to assemble automatically) 8. Beans related properties in tags

Default-init-method
Default-destory-method
Default-autowire: The default is None, apply to all beans in the spring configuration file, note that this does not refer to the spring application context, because you can define multiple profile 9. Bean's life cycle

1) Create an instance of the bean (Factory-method, autowireconstrutor)  
2) attribute injection (Autowirebyname, autowirebytype)  
3) Initialize BEAN 
3.1 Activates the Aware method: (Invokeawaresmethods) Some aware related interfaces are provided in spring, such as Beannameaware, Beanfactoryaware, Applicationcontextaware, the bean that implements these aware interfaces can get some corresponding resources after being initialized.

 private void invokeawaremethods (final string beanname, final object Bean) {   if (bean instanceof aware)    {       IF (bean instanceof  Beannameaware) {            ((beannameaware) beans). Setbeanname (Beanname);     & nbsp &NBSP,}        if (bean instanceof beanclassloaderaware) {            ((beanclassloaderaware) bean). Setbeanclassloader (Getbeanclassloader ());        }        if (bean instanceof beanfactoryaware) {    & nbsp       ((beanfactoryaware) bean). Setbeanfactory (Abstactautowire capablebeanfactory.this);        }    }} 

Application of the

3.2 processor (Beanpostprocessor interface) : The Postprocessbeforeinitialization and Postprocessafterinitialization methods of the beanpostprocessor are called before the customer's custom initialization method is called and after the custom initialization method is called So that users can respond to their business needs.  
3.3 Activating a custom Init method (Init-method & Custom Implementation Initializingbean interface)

Protected object initializebean (final string beanname, final object Bean, Rootbeandefinetion mbd) {   if (System.getsecuritymanager ()!= null) {        Accesscontroller.doprivileged (New privilegedaction<object> () {           @ override            public object run ()           & nbsp {               invokeawaremethods (Beanname,bean),         &N Bsp      return null;            }        });    }    else{       //for Special bean Processing: Aware, Beanclassloaderaware, Beanfactoryaware         invokeawaremethods (Beanname,bean);    }    object wrappedbean = bean;   &NBSP;IF (mbd == null !!! mbd.issynthetic ()) {       wrappedbean = applybeanpostprocessorsbeforeinitialization (wappedbean,beanname);    }    try{       invokeinitmethods (Beanname, Wappedbean, mbd);    } & nbsp  catch (Throwable ex) {       throw new beancreationexception (mbd!= null  ? Mbd.getresourcedescription (): null), Beanname, "Invocation of Init method failed", ex);    }    if (mbd == null | |. Mbd.issynthetic ()) {       wrappedbean = Applybeanpostprocessorsafterinitialization (Wrappedbean, Beanname);    }    return wappedBean; }


4) Use beans. resides in the context of the app until the app context is destroyed.
5) Destroy (Destory-mthod & implement Disposablebean Interface)

Or represent like this:
1. Bean's Construction
2. Call the Setxxx () method to set the Bean's properties
3. Call Beannameaware's Setbeanname ()
4. Call Beanfactoryaware's Setbeanfactory () method
5. Call Beanpostprocessor's Postprocessbeforeinitialization () method
6. Call Initializingbean's Afterpropertiesset () method
7. Invoking a custom initialization method
8. Call the Postprocessafterinitialization () method of the Beanpostprocessor class
9. Call Disposablebean's Destroy () method
10. Call the custom Destroy method 10. Inject collections in spring

<list> allowable values are the same

<set> does not allow the same value

<map><entry key= "" value= "" ></map> keys and values can be any type, key, Key-ref, Value-ref, value can be any match

<props><prop key= "" >XXX</prop></props> keys and values can only be string type 11. assembly NULL Value

<property name= "xxx" ><null/></property>
12. Automatic assembly (autowiring)

Helps reduce or even eliminate configuration <property> and <constructor-arg> elements, allowing spring to automatically identify how the bean's dependencies are assembled. <context:annotation-config/>
This corresponds to Automatic detection (AutoDiscovery), which is a step closer to automatic assembly, allowing spring to automatically identify which classes need to be configured as Springbean, thus reducing the use of <bean> elements. <context:component-scan> 13. Annotations

The spring container disables annotation assembly by default. The simplest way to open <context:annotation-config/>.
Some of the different annotations that spring supports for automatic assembly:

Spring comes with @autowired annotations

@inject Annotations of JSR-330

JSR-250 's @resource note . @Autowired

@Autowired have strong contractual characteristics, and the attributes or parameters they label must be assembled. If no bean can be assembled into a property or parameter marked by @autowired, the automatic assembly fails and throws Nosuchbeandefinitionexception.
The property does not have to be assembled, and the null value is acceptable. In this scenario, it is optional to configure automatic assembly by setting the required property of @autowired to False, such as:

@Autowired (required= false) private Object obj;

Note the Required property can be used anywhere the @autowired annotation is used. However, when using a constructor assembly, only one constructor can set the required property of @autowired to True. Other constructors annotated with @autowired annotations can only set the required property to False. In addition, when multiple constructors are labeled with @autowired, Spring selects the one with the most parameters from all constructors that meet the assembly criteria.
You can use @qualifier to explicitly specify which beans to assemble. The following:

@Autowired @Qualifier ("objname") private Object obj; 15. Custom Qualifiers
@Target ({elementtype.fielf, elementtype.parameter, Elementtype.type}) @Retention (retentionpolicy.runtime) @ Qualifier Public @Interface specialqualifier{}


At this point, you can use the custom @specialqualifier annotations instead of the @qualifier to annotate them, or you can work with @autowired:

@Autowired @SpecialQualifier private Object obj;

At this point, spring reduces the range of automatic assembly to the bean that is @specialqualifier labeled. If there are more than one bean labeled by @specialqualifier, we can further narrow the scope by customizing another qualifier @specialqualifier2. . @Autowired advantages and Disadvantages

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.