Discard the configured Spring Ultimate Tutorial

Source: Internet
Author: User
Tags aop object object
A: Preface

Spring has two versions of XML configuration and annotations, and I personally like the use of annotations, quite enthusiastic about spring boot!

For spring, the core is the IOC container, which is plainly the object (Bean) you put in the unified management, you do not have to consider how the object to create how to destroy, in this regard, the so-called inversion of control is the way to get the object is reversed.

Since you have given the object to someone else spring management, you should not give it to others when you need it. This is Dependency injection (DI)! Think again, when we pass in a parameter in addition to the constructor method is in the setter method, a good name is the construction injection and set value injection .

As for AOP ( aspect-oriented ), I would like to cite an example, for example, you write a method to do something, but this thing requires the login user to do, you can verify this method before execution, record the operation log after execution, To extract the pre-and post-business-logic-independent code out of a class, this class is the tangent (Aspect), the wrapping method is the tangent Point (Pointcut), you do the execution before the execution of these methods are called enhanced processing (Advice).

Two: Configuration

We recommend using idea to quickly build a spring project!

Discard configuration First step, quickly define Application.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:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    <!--开启自动扫描-->    <context:component-scan base-package="cn.zyzpp"/></beans>

Role

    1. The default scan spring provides classes for annotations such as @component, @Repository, @Service, @Controller, @RestController, @ControllerAdvice, and @configuration.
    2. annotation annotation configuration is enabled by default, activating @required, @Autowired, @PostConstruct, @PreDestroy, @Resource, @PersistenceContext, @ Persistenceunit the comments in the component class.
Three: Dependency Injection Search Bean class

Spring provides several annotation to annotate spring beans:

    • @Component: Label a normal spring Bean class
    • @Controller: Labeling a Controller component class
    • @Service: Labeling a business logic component class
    • @Repository: Labeling a DAO component class
Configuring Dependencies using @resource

Use @Resource the <property.../> same effect as the ref attribute of an element.

@ResourceNot only can you modify the setter method, you can also directly modify the instance variables, if the use @Resource of modified instance variables will be more simple, when spring will be directly using the Java EE Specification field injection, at this time even setter method can not.

@ResourceLocated javax.annotation under the package, is one from the Java EE specification Annotation .

@Resource There are two attributes that are important, the name and type,spring the Name property of the @resource annotation to the bean's name, and the type attribute to the Bean's. So if you use the Name property, you use the ByName Auto-injection policy, and the Type property uses the Bytype auto-injection policy. If neither name nor the type attribute is specified, the ByName auto-injection policy is used through the reflection mechanism.

Configuring Dependencies using @autowired

Spring provides @Autowired annotations to specify automatic assembly, which @Autowired can be used to modify setter methods, common methods, instance variables, and constructors. When using @Autowired the label setter method, the Bytype automatic assembly policy is used by default.

By default @Autowired(required = true) , it means that a dependent object must exist.

Paired with @qualifier designation Beanid

In this strategy, there are often multiple candidate bean instances that conform to the automatic assembly type, which can cause an exception at this time, and in order to achieve precise automatic assembly, Spring provides @Qualifier annotations that, by use @Qualifier , allow automatic assembly to be performed based on the Bean's ID.

    @Autowired    @Qualifier(value = "user")    User user;
Four: Define Bean@configuration configuration

@Configuration is used to define a configuration class that can replace an XML configuration file, and the annotated class contains one or more methods that are @bean annotated. These methods will be scanned by the Annotationconfigapplicationcontext or Annotationconfigwebapplicationcontext class and used to build the bean definition to initialize the spring container.

 @Configuration public class AppConfig {     @Autowired      Environment env;     @Bean     public MyBean myBean() {         MyBean myBean = new MyBean();         myBean.setName(env.getProperty("bean.name"));         return myBean;     } }
@Bean definition

The difference between @Bean and Component is in the method, not on the class. Similar to XML <bean/> . The default bean name is called the method name.

If you need an explicit name, you can use the Name property (or the Value property). Also note that name accepts an array of strings, allowing multiple names (that is, the main bean name plus one or more individual names) to be used on a single bean.

You can define a bean's initialization method and the method that is called when the application is closed.

     @Bean({"b1", "b2"},initMethod = "",destroyMethod = "") // 有b1,b2 bean,但没有myBean     public MyBean myBean() {         return new MyBean;     }
@Scope Scope

@Scope can define the scope of the bean with @component or @bean annotations. The default scope Singleton.

Scope Description
Singleton There is only one bean instance in the spring IOC container, and the bean exists in singleton, the default value
Prototype Each time a bean is called from the container, a new instance is returned, which is equivalent to executing newxxxbean () whenever Getbean () is called.
Request Each HTTP request creates a new bean that applies only to the WEBAPPLICATIONCONTEXT environment
Session Share a bean with the same HTTP session, different sessions using different beans, only for the WEBAPPLICATIONCONTEXT environment
Global-session Typically used in a portlet application environment to be used only for webapplicationcontext environments

Example

@Component@Scope(value = "singleton")public class HelloWord {
@Lazy Lazy Loading

The @Lazy is used with @component or @bean to delay initializing the bean and tell the IOC container to create a bean instance when it is first requested, rather than at startup.

@Component@Lazypublic class HelloWord {
@PostConstruct and @predestroy customizing life cycle behavior

@PostConstructand @PreDestroy two annotation,spring from the Java EE specification, also located under the Javax.annotation package, are used to customize the life cycle behavior of the bean in the spring container.

They are all used to modify the method without any attributes.

Where the former modifies the method when the bean initializes the method, while the latter modifies the method when the bean is destroyed before the method.

V: Using AOP

AOP (Aspect Orient programming) is the aspect-oriented programming, as a complement to object-oriented programming, has become a relatively mature programming method. In fact, the time of AOP is not too long, AOP and OOP complement each other, aspect-oriented programming to break down the process of running the program into various facets.

AOP is specifically designed to address cross-focus issues in systems distributed across modules (different approaches), and in Java EE applications, some system-level services with crosscutting properties, such as transaction management, security checks, caching, object pool management, are often handled through AOP. AOP has become a very common solution.

Configure Open AOP
  <!--启动@AspectJ支持-->  <aop:aspectj-autoproxy/>  <!--指定自动搜索Bean组件、自动搜索切面类-->  <context:component-scan base-package="cn.zyzpp">    <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>  </context:component-scan>
@Aspect Defining facets

@Aspect cannot be scanned, so it is necessary to cooperate with @component annotations. @Aspect identifies itself as a facet and removes itself from the automatic proxy.

@Aspectpublic class AspectModule {}
@Pointcut Defining pointcuts

Note that the tangent point is defined by a normal method, and the return type must be void. Supports execution expressions, within expressions, for example:

@Pointcut("execution(* cn.zyzpp.demo.*Word.*(..))")private void businessService() {}  // signature

The first * represents any return type, divided by the. Number, followed by the package name, the class name, the class name followed by the method name, the method name followed by parentheses, and the arguments in parentheses, two points: It means any parameter.

Other usage reference AOP expression usage

Advice enhanced Processing
Annotations explain
@Before Pre-Notification: The target method executes the contents of the following method body before executing
@After Post notification: The target method executes after executing the contents of the following method body, regardless of whether an exception occurred.
@AfterReturning Return notification: Execute the following code when the target method finishes executing properly
@AfterThrowing Exception notification: The target method executes the following code when an exception occurs
@Around Surround Notification: Execute some code before and after the target method executes, and execute additional code when an exception occurs

Execution order

Joinpoint getting the target method

The simplest way to access the target method is to define an enhanced processing method, define the first parameter as the Joinpoint type, and when the enhanced processing method is called, the Joinpoint parameter represents the join point for weaving the enhanced processing. The joinpoint contains the following common methods:

    • Object[] Getargs: Returns the parameters of the target method
    • Signature getsignature: Returns the signature of the target method
    • Object Gettarget: Returns the target object that was woven into the enhanced processing
    • Object Getthis: Returns the proxy object generated by the AOP framework for the target object
Custom annotations to advice parameters

@Retention define the life cycle of custom annotations

    1. Retentionpolicy.source: Annotations only work in Java source files (. java files) and are not compiled into class bytecode files.
    2. Retentionpolicy.class: Annotations are persisted to the class file and discarded when the JVM loads the class file for the default life cycle
    3. Retentionpolicy.runtime: Annotations exist in the source file and class and can be loaded by the JVM and retrieved dynamically at run time.

@Target Define where annotations work

    • Elementtype.type//interfaces, classes, enumerations, annotations
    • Elementtype.field//fields, enumerated constants
    • Elementtype.method//method
    • Elementtype.parameter//Method parameters
    • Elementtype.constructor//Constructors
    • elementtype.local_variable//local variables
    • Elementtype.annotation_type//annotations
    • Elementtype.package///bag

@Documented, @Inherited Ignore!

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface Annota {    String value();}

Use this annotation in the target method

    @Annota("Mark")    public void say(String name){        ....    }
Full AOP Example
@Component @aspectpublic class Myaspect {//declares tangency @Pointcut ("Execution (* cn.zyzpp.demo.*word.* (..))") public void Pointcut () {}//declares tangency @Pointcut ("Within (cn.zyzpp.demo.*)") public void Bizpointcut () {}//Pre-notification: Target    The method executes the contents of the following method body before executing @Before ("pointcut ()") public void before () {System.out.println ("before"); }//Pre-notification: Get annotations, pass parameters to advice @Before ("pointcut () && @annotation (Annota)") public void Beforewithannotaio    N (Annota Annota) {System.out.println ("beforewithannotation:" + annota.value ()); }//Pre-notification: Gets the parameter @Before ("Pointcut ()") public void Beforeargs (Joinpoint joinpoint) {for (Object Object:joinpo        Int.getargs ()) {System.out.println ("before args:" +object.tostring ()); }}//Pre-notification: Gets the object @Before ("Pointcut () && args (ARG)") public void Beforewithpar (object arg) {Syste    M.out.println ("Before obj:" +arg.tostring ());    }//Post notification: The target method executes after executing the contents of the following method body, regardless of whether an exception occurred. @After ("PoIntcut () "public void After () {System.out.println (" after "); }//Return notification:: Execute the following code @AfterReturning (pointcut= "bizpointcut ()", returning= "Retrunvalue") public void Afterr when the target method has completed normal execution    Eturning (Object retrunvalue) {System.out.println ("afterreturning:" +retrunvalue); }//Exception notification: The target method executes the following code when an exception occurs @AfterThrowing (pointcut= "pointcut ()", throwing= "E") public void afterthrowing (Runtimee    Xception e) {System.out.println ("afterthrowing:" + e.getmessage ()); //Surround Notification: The target method executes some code before and after execution, and executes some additional code @Around ("Pointcut ()") Public Object Around (Proceedingjoinpoint PJP) When an exception occurs THR        oWS throwable {System.out.println ("Around:start");        Object obj = Pjp.proceed ();        System.out.println ("Around:end, Return:" +obj);    return obj; }}
VI: the management of Things

A database transaction is a sequence of operations that is considered a single unit of work. These operations should either be performed completely or not at all. Transaction management is an important part of an RDBMS for enterprise applications to ensure data integrity and consistency. The concept of a transaction can be described as having the following four key properties that are said to be ACID:

    • atomicity: A transaction should act as a single unit, which means that the entire sequence operation is either successful or failed.
    • Consistency: This represents the consistency of referential integrity of the database, the only primary key in the table, and so on.
    • Isolation: Many transactions with the same data set may be processed at the same time, and each transaction should be isolated from other transactions to prevent data corruption.
    • Persistence: Once a transaction has completed its entire operation, the result of the transaction must be permanent and not be removed from the database due to a system failure.
Programmatic vs. declarative

Spring supports two types of transaction management:

    • Programmatic transaction management: This means that you have a management transaction with the help of programming. This gives you a great deal of flexibility, but it's hard to maintain.
    • Declarative transaction management: This means that you detach transaction management from the business code. You only use annotations or XML configurations to manage transactions.

Declarative transaction management is preferable to programmatic transaction management, although it is less flexible than programmatic transaction management, but it allows you to control transactions through code.

Annotation-based approach

1. Turn on the transaction

    <!-- 初始化 数据源 -->    <bean id="dataSource"          class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="com.mysql.jdbc.Driver" />        <property name="url" value="jdbc:mysql://localhost:3306/TEST" />        <property name="username" value="root" />        <property name="password" value="123456" />    </bean>    <!-- 事务管理器配置 -->    <bean id="transactionManager"          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource" />    </bean>    <!-- 使用annotation注解定义事务 -->    <tx:annotation-driven transaction-manager="transactionManager"/>

2.service class @transactional (Name=value)

@Transactional parameters

Parameter name Function Description
ReadOnly This property is used to set whether the current transaction is a read-only transaction, set to True for read-only, false to read-write, and the default value to False. Example: @Transactional (readonly=true)
Rollbackfor This property is used to set an array of exception classes that need to be rolled back, and when the method throws an exception in the specified exception array, the transaction is rolled back. For example: Specify a single exception class: @Transactional (Rollbackfor=runtimeexception.class) specifies multiple exception classes: @Transactional (rollbackfor={ Runtimeexception.class, Exception.class})
Rollbackforclassname This property is used to set an array of exception class names that need to be rolled back, and when the method throws an exception in the specified exception name array, the transaction is rolled back. For example: Specify a single exception class name: @Transactional (rollbackforclassname= "runtimeexception") specifies multiple exception class names: @Transactional ( rollbackforclassname={"RuntimeException", "Exception"})
Norollbackforclassname This property is used to set an array of exception class names that do not need to be rolled back, and when a method throws an exception in the specified exception name array, the transaction is not rolled back. For example: Specify a single exception class name: @Transactional (norollbackforclassname= "runtimeexception") specifies multiple exception class names: @Transactional ( norollbackforclassname={"RuntimeException", "Exception"})
Propagation This property is used to set the propagation behavior of a transaction. Example: @Transactional (propagation=propagation.not_supported,readonly=true)
Isolation This property is used to set the transaction isolation level of the underlying database, which is used to handle multi-transaction concurrency, usually using the default isolation level of the database, and does not need to be set
Timeout This property is used to set the time-out seconds for a transaction, and the default value is 1 to never time out
End

This article for my hard code word half-day results, incidentally review the knowledge of spring, flowchart with the word~~

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.