Knowledge point shorthand for the IOC and AOP of Java spring

Source: Internet
Author: User

Spring Introduction

One of the core issues that spring solves is to shift the dependencies between objects into a configuration file, which is implemented through spring's dependency injection mechanism.

Spring Bean Assembly

1. The IOC concept and how the IOC operates in the spring container.

Ioc:inversion of control, inversion of controls. In Java development, IOC means that the class you have designed is given to the system to control, not within your class, which is called control inversion, that is, the instance of the called class is created by the original invocation class control, and the destruction is now transformed into a container managed by spring.

2. How the Spring container manages the bean's life cycle (e.g., bean initialization method, bean destruction method)

Created: <bean name= "" class= "" Extra Properties >

Initialize: Configure Init-method/Implementation Interface Initializingbean

Call: Context.getbean (), making a call to the method

Destroy: Configure destroy-method/to implement Disposablebean interface

3. The concept of Di and the injection in spring framework are several ways. What problems do you have to pay attention to when using constructs to inject objects?

Injection method:

Construction injection [construction method injection]

attribute injection [Set/get of attributes]

Method injection [Factory injection]

<!--Constructor Injection -<BeanID= "User1"class= "Com.spring.test.model.User">    <Constructor-argIndex= "0"type= "String"value= "Lu"></Constructor-arg>    <Constructor-argIndex= "1"type= "String"value= "123456"></Constructor-arg></Bean><!--Attribute Injection -<BeanID= "User2"class= "Com.spring.test.model.User">    < Propertyname= "username"value= "Luxx"></ Property>    < Propertyname= "Password"value= "56789"></ Property></Bean><!--Factory Injection -<BeanID= "Userfactory"class= "Com.spring.test.factory.UserFactory"/><BeanID= "User3"Factory-bean= "Userfactory"Factory-method= "CreateUser"></Bean><!--Static Factory injection -<BeanID= "User4"class= "Com.spring.test.factory.UserFactoryStatic"Factory-method= "CreateUser"></Bean>

When using a constructor dependency injection, spring guarantees that all objects dependent on all objects are instantiated before instantiating the object. When using the Set method dependency injection, spring instantiates the object first and then instantiates all dependent objects.

4. When using Di injection, the property represents what it means, if the property refers to another bean, how to inject, if the reference is a string, how to set.

When using Di injection, the property represents the attribute of the injected class, and if the other bean is applied with a ref attribute to indicate the name of the referenced bean, if it is a reference string, use the Value property. Such as:

<name ref/> < name = " string"/> 

5. Scope of Beans

The default for all spring beans is singleton, which is scope= "singleton"

Several scopes:

Singleton: In each spring container, a bean defines only one instance of an object.

The definition of Prototype:bean can be instantiated any time (each invocation creates an instance).

Request: In one HTTP request, each bean definition corresponds to an instance. The scope is valid only in a Web-based spring context, such as spring MVC.

Session: In an HTTP session, each bean definition corresponds to an instance. The scope is valid only in a Web-based spring context, such as spring MVC.

Global-session: In a global HTTP session, each bean definition corresponds to an instance. The scope is valid only in the context of the portlet.

6. Di automatic assembly (autowiring)

Spring provides a mechanism for automating the assembly of dependent objects, but it is not recommended to use automatic assembly in practical applications, because automatic assembly creates an unknown situation and the developer cannot foresee the final assembly result.

Automatic assembly is implemented in the configuration file, as follows:

<id= "* * *"  class= "* * * " autowire= "ByName " >

You only need to configure one @autowired property to complete the automatic assembly, no more write <property> in the configuration file, but in the class you want to build the setter method of the dependent object.

The Autowire property values are as follows:

1) byname is assembled by name, the bean with the same property name (or ID) can be queried in the container based on the name (or ID) of the property, and if not found, the property value is null;

2) Bytype by type, you can search for the type of bean in the container according to the property type, if there are more than one, throw an exception, if not found, the property value is null, if there are more, use the bean's Primary property, note: This default is true, The primary property of the non-candidate bean needs to be set to false. Exclude certain beans and set the Autowire-candidate property of some beans to false.

3) constructor is similar to the bytype approach, where it is applied to the constructor parameter, and throws an exception if no bean is found in the container that matches the constructor parameter type.

4) AutoDetect uses the Bean class's introspection mechanism (introspection) to determine whether to automate assembly using constructor or Bytype. First try to use constructor for automatic assembly. If it fails, try to use the Bytype method again.

Optional automatic assembly: By default, the @Autowired has a strong contract attribute, the attributes or parameters that are marked must be assembly, and if not, the automatic assembly fails (throws Nosuchbeandefinitionexception). The property does not have to be assembled, and the null value is acceptable, and configuration with @autowired (Required=false) is optional.

Ambiguous dependency: Use @qualifier ("Bean ID") to narrow the selection to just one bean by making the Bean's ID.

Note: Explicitly specifying dependencies, such as property and constructor-arg elements, will always overwrite the auto-assembly. Automatic assembly behavior can be used in conjunction with dependency checking, which occurs after automatic assembly is complete.

7. Di automatic Detection (autodiscovery)

Configure spring to automatically detect bean definitions and automatically assemble beans:

<context:component-scan base-package= "Com.spring.test"/>

By default,,<context:component-scan> looks for classes that are annotated with stereotype annotations, which are as follows:

@Component a generic stereotype annotation that identifies the class as a spring component.

@Controller identifies the class as a spring MVC Controller.

@Repository identifies the class as a data warehouse, generally as a DAO layer annotation.

@Service identifies the class as a service, typically as a service layer annotation.

Any custom annotations that use @component annotations.

Spring AOP

What are the benefits of the concept of AOP and the use of AOP mechanisms?

The concept of AOP is aspect oriented programming programming for facets.

Benefit: AOP breaks down the program into various aspects or concerns, which makes it modular and quite horizontally cut. It solves crosscutting (cross-cutting) issues such as transaction, security, logging, and other crosscutting concerns that are not well addressed by OOP and procedural methods.

2 ways to implement AOP in Java spring:

1) Implement AOP using annotations (@AspectJ):

@Aspect @component Public classlogaspect {@Before ("Execution (Public * com.spring.test.service.*.* (..))")     Public voidBeforeservice () {System.out.println ("Before ..."); } @After ("Execution (Public * com.spring.test.service.*.* (..))")     Public voidAfterservice () {System.out.println ("After ..."); } @AfterReturning ("Execution (Public * com.spring.test.service.UserService.save(Com.spring.test.model.User) and args (User)") Public voidlogafterreturn (user user) {System.out.println ("After return ..." +user); }}

To turn on annotation scanning:

XMLNS:AOP=HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP Www.springframework.org/schema/aop/spring-aop-3.2.xsd<Context:component-scan base-package  = "com.spring.test"/><aop:aspectj-autoproxy/>

2) Another way to configure XML:

 Public class Logaspect {    publicvoid  Beforeservice () {        System.out.println ("before ...");    }          Public void Afterservice () {        System.out.println ("After ..."        );  Public void logafterreturn (user user) {        System.out.println ("after return ..." +User);}    }

Configuration:

<BeanID= "Logaspect"class= "Com.spring.test.aop.LogAspect" /><Aop:config><Aop:aspectref= "Logaspect">    <Aop:pointcutID= "Serviceaction"expression= "Execution (public * com.spring.test.service.*.* (..))"/>    <Aop:beforepointcut-ref= "Serviceaction"Method= "Beforeservice"/>    <Aop:afterpointcut-ref= "Serviceaction"Method= "Afterservice"/>        <Aop:pointcutid= "Servicereturnaction"expression= "Execution (public * Com.spring.test.service.UserService.save (Com.spring.test.model.User)) and args (User)" />    <Aop:after-returningpointcut-ref= "Servicereturnaction"Method= "Logafterreturn"Arg-names= "User"/></Aop:aspect></Aop:config>

Reference:

Http://docs.spring.io/spring/docs/current/spring-framework-reference/html/index.html

Http://oss.org.cn/ossdocs/framework/spring/zh-cn/beans.html

Knowledge point shorthand for the IOC and AOP of Java spring

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.