spring base -AOP, JdbcTemplate

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_40918961/article/details/94877841

AOP- Oriented Programming

        AOP OOP is a useful addition to, features of object-oriented inheritance, polymorphism and encapsulation. Requires encapsulated into different functional objects go, often referred to as the allocation of responsibilities in the software design. That fact, so that different classes of different design methods. Such code is dispersed into a class of one go. The benefit of this is to reduce the complexity of the code, the class can be reused.
        But at the same time dispersing the code, but also increased the repetitive code. What does that mean? For example, we have two classes, you may need to do logging in each method. By object-oriented design methods, we must have joined the contents of the log in the two class method. Maybe they are exactly the same, but that is because between object-oriented design allows the class and the class can not be contacted, and not be able to unify these duplicate code.
        Of course, we can write this code in a separate class in an independent way, then call in these two classes. However, this way, these two classes with separate classes we mentioned above there are a couple, it's change will affect these two categories. So, is there any way to get us in time of need, casually adding code? In this operation, the code to dynamically cut into specified class methods, programming ideas specified position on the cut surface is oriented programming.
        In general, we cut the tube to the specified code snippets cut method specified class is called, and which cut into the class, which is called the entry point methods. With AOP, we can put a few common class of code, drawn into a slice, until the need to cut into the object to, thereby changing its original behavior.

AOP is such a design idea, commonly used dynamic proxy to achieve, which has been widely applied to various frameworks, it can be seen as interceptors.

AOP using dynamic proxy general idea, java or third-party libraries in Proxy cglib to achieve, if not understand the dynamic proxy, please refer to: | -------- -------- Portal | |

In Spring AOP

in the spring using AOP cglib to achieve complete different cut through the realization of four different interfaces.

Specifically, one write a Bean, some public non-final methods that need to be cut into the Bean 2. Write a generic proxy class that implements an interface corresponding to the two bean and Configuration dependencies, and configure the master agent i.e. class = org.springframework.aop.framework.ProxyFactoryBean.

MethodBeforeAdvice

The interface has a method public void before (Method method, Object [] args, Object target) throws Throwable

method represents a cut method, args said its parameters, target of Bean said to be cut

It indicates override this method before performing the method will first execute the code before () in

After Returning Advice

有方法afterReturning(Object returnValue, Method method, Object[] args, Object target)throws Throwable

Supra, override this method indicates the method after performing the afterReturning executes the code () in

ThrowsAdvice

有方法public void afterThrowing(IllegalArgumentException e) throws Throwable

Ibid, override this method represents an exception is thrown IllegalArgumentException executes the code afterReturning () in the execution method

MethodInterceptor

There Method public Object invoke (MethodInvocation methodInvocation)

Implementation of the original method by calling methodInvocation.proceed ()

Example:

1. Write bean

public class CustomerService {

    private String name;
    private String url;

    public void setName(String name) {
        this.name = name;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void printName() {
        System.out.println("Customer name : " + this.name);
    }

    public void printURL() {
        System.out.println("Customer website : " + this.url);
    }

    public void printThrowException() {
        throw new IllegalArgumentException();
    }

}

2. Write the Common Agent

public class LslBeforeMethod implements MethodBeforeAdvice {

    public void before(Method arg0, Object[] args, Object target)
            throws Throwable {
        System.out.println(" Before method ");

    }

}

3. Configure dependencies

<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="customerService" class="CustomerService">
        <property name="name" value="S" />
        <property name="url" value="http://lsl----lsl.com" />
    </bean>

    <bean id="lslBeforeMethodBean" class="LslBeforeMethod" />

    <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="customerService" />
        <property name="interceptorNames">
            <list>
                <value>lslBeforeMethodBean</value>
            </list>
        </property>
    </bean>

</beans>

After CustomerService of methods will be intercepted LslBeforeMethod were each execution.

Precise cut by the method name or a regular match

The above configuration makes all the methods have been intercepted, in order to be more flexible precise cut, spring to prepare a variety of configurations.

Specific 1.org.springframework.aop.support.DefaultPointcutAdvisor refers to the default agent 2.pointcut: designated entry points, advice: designated agent

<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="customerService" class=CustomerService">
        <property name="name" value="ad" />
        <property name="url" value="asd" />
    </bean>

    <bean id="lslAroundMethodBean" class="LslAroundMethod" />

    <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target" ref="customerService" />
        <property name="interceptorNames">
            <list>
                <value>customerAdvisor</value>
            </list>
        </property>
    </bean>

    <bean id="customerPointcut" class="org.springframework.aop.support.NameMatchMethodPointcut">
        <property name="mappedName" value="printName" />
    </bean>

    <bean id="customerAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <property name="pointcut" ref="customerPointcut" />
        <property name="advice" ref="lslAroundMethodBean" />
    </bean>

</beans>

That agent becomes org.springframework.aop.support.DefaultPointcutAdvisor

Specifies the cut by specifying pointcut method

By specifying advice agency designated to perform

If you are using a regular, then the pointcut become patterns, that is replaced

  1. <property name="patterns">
  2.     <list>
  3.         <value>.*URL.*</value>
  4.     </list>
  5. </property>

AspectJ

Annotation can be done by using the form AOP, AspectJ is a third-party libraries, static directly weaving the automatically generated proxy class.

AspectJ annotation types supported are as follows:

  • @Before
  • @Aspect
  • @After
  • @AfterReturning
  • @AfterThrowing
  • @Around

Use Aspectj can add dependencies

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.2</version>
        </dependency>

Note the replacement version

Statement added pom.xml <aop: aspectj-autoproxy />

@Aspect used to declare a class, it indicates that the class is a class section, after using annotations to specify a method of a class, static weaving

1. Declare common bean

@Component("bean")
public class TestMethod {

    public void before(String name) {
        System.err.println("the param Name is " + name);
    }

    public void after(String name) {
        System.err.println("the param Name is " + name);
    }

    public void around(String name) {
        System.err.println("the param Name is " + name);
    }
}
 

2. Statement section Aspect

@Aspect
@Component
public class ExecutionAspect {

    @Before ( "Execution (club.myapp.aspectJ *. *. * Before (..))")
    public void doBefore (the JoinPoint Joinpoint) throws the Throwable {
        System.err.println ( "This is a pre-notification, in the process before the call is executed !!! ");
    }

    @After ( "Execution (club.myapp.aspectJ *. *. * After (..))")
    public void doAfter (the JoinPoint Joinpoint) throws the Throwable {
        System.err.println ( "This is a post-notification, in the process after the call is executed !!! ");
    }

    @Around ( "Execution (club.myapp.aspectJ *. *. * Around (..))")
    public void doAround (ProceedingJoinPoint Joinpoint) throws the Throwable {
        System.err.println ( "which is surrounded by a notification, the method call will be executed before and after !!! ");
        System.err.println (" before execution ");
        joinPoint.proceed ();
        System.err.println (" after performing ");
    }
}
 

 For information "execution (* club.myapp.aspectJ * before * (..)..)" Is: first * indicates the return type (* indicates any type of return value) followed by the absolute path of a method, You can use a regular match.

JdbcTemplate

Spring JDBC package comes with a reinforcing function of a class.

To add a dependent use:

<name>springJdbc</name>

<url>http://maven.apache.org</url>

  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

Configure data source, introducing bean

<?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:annotation-config/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/test?serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

Examples of use can create JdbcTemplate

        JdbcTemplate jdbcTemplate=(JdbcTemplate) context.getBean("jdbcTemplate");
        String sql="insert into student values(?,?,?)";
        int count=jdbcTemplate.update(sql,new Object[]{2,"shiyanlou2",18});
        System.out.println(count);

As shown above, JdbcTemplate built multiple methods for sql, in fact, it is to be further packaged JDBC

You can pass a DAO.class return RowMapper <DAO> object query execution ORM mapping

RowMapper<Student> rowMapper=new BeanPropertyRowMapper<Student>(Student.class);
List<Student> list=jdbcTemplate.query(sql,rowMapper);
for(Student student:list){
    System.out.println(student.getId()+" "+student.getName());
}

 

Guess you like

Origin blog.csdn.net/qq_40918961/article/details/94877841