Spring (ii) of Aop, AspectJ and JdbcTemplate

A, Aop [ Aspect Oriented Programming ] (Aspect Oriented Programming)

1 Overview:

         By precompiled dynamic proxies to implement a unified program features technical maintenance of way and run. AOP is OOP continuation, is a hot spot in software development, but also Spring an important element of the framework is the functional programming a Yansheng Fan type. AOP can use to isolate each part of the business logic such that the business logic portions between coupling reduction , improve the reusability of the program , while improving the efficiency of development .

       Advantages: ① good isolation between the respective steps; ② source independence.

       Disadvantages: difficult to use. You need to achieve a large number of interfaces, inherits a lot of class.

2, the main function: logging, performance statistics, security control, transaction processing, exception handling , and so on.

3, the main intent: logging, performance statistics, security control, transaction processing, exception handling , etc., code division from the business logic code out by the separation of these acts, we hope they can be independent non-guide business logic methods in, and then change the behavior of the time does not affect the business logic code.

. 4, A OP implementation principle: ① achieved through a proxy mechanism; the interface and implementation class : may be employed JDK Proxy to generate a proxy object; ③ has no implementation class and interface implementation class interfaces are cglib bytecode may be employed to enhance the Implementing a proxy.

5, Aop term

 notice (the Advice) : Want to realize the function, that is to say above safety, things, logs.

connection point (the JoinPoint) : where is the spring to allow the use of the notification , when the basic front of each method, after (both also OK), or throwing an exception may be the connection point, spring only supported method for connecting point. others such as aspectJ also lets you in the constructor or property injection will do.

      ③ entry point (Pointcut) : calling a before a few ways to do something after or throws an exception, then use cut into points to define these methods, so that the cut -in point to point connection filter, check that a few a way you want.

     ④ section (Aspect) : section is a combination of notice and entry points. ( No connection point what the connection point is to let hello to understand the point of tangency, out out, understand this concept on the line.) Notice explains what to do and when dry (when by the method name in the before, after, around and so be able to know), and describes the entry point where dry (designated in the end is which method), which is a complete cut definition. ( ? What is a knife to cut a watermelon into two, cut incision is cut; cooking pot and stove together to complete the cooking pot and the stove is cut .web-level design, web Layer -> Layer Gateway -> Services layer -> data layers, is a programming section, between the object and the object, between the method and the method, between the module and the module is between each layer of one slice . )

    ⑤ introduced (Introduction) :  it allows us to add new methods to an existing class attribute. Equivalent to the section (that is, the new method attribute: notification defined) used in the target class.

    ⑥ target (target) : target class mentioned in the introduction, the object is to be notified, the business logic is true, it may be the case without the knowledge, we are weaving section. While it focused on the business logic itself.

     ⑦ proxy (Proxy) : It allows Spring dynamically generates a new class that implements the necessary interfaces, weaving notice, and to any calls to these interfaces are forwarded to the target class.

    ⑧ weaving (Weaving) : the section applied to the target object to create a new proxy object process  

 . 6, Spring section wrapped with a proxy class, weaving them into Spring managed bean. That proxy class disguised as a target class, which intercepts calls to the target class method, so that the caller calls to the target class have become the first class to call camouflage, camouflage class on the first section is performed, then call forwarding to the real target bean.

  Now you can think about yourself, how do come out of this disguise class, the caller will not be found (by examining the JVM, JAVA is a strong type checking, checking where every type).

  (1)  to achieve the same target class interface , I also like you to realize the interface anyway upper level of calls are interfaces, so I disguised the same class and target class (implement the same interface, they are brothers a), also escaped the type checking, the java runtime when using late-binding polymorphism (adopted so when spring run), camouflage class (proxy class) becomes a real implementation of the interface, while he inside the parcel, the true goal of the class, and finally achieve a particular functionality or target class, just pretend like something did before (to write the log, security checks, transactions, etc.).

  It's like, you make a person do something, every time this time, your brother will come out first, of course, he was too close to call, and thought it was you, you can not do this brother Although this matter, but he knows you can do , so I agreed down, and received a little gift (write logs), harvested gift, give something to the people to do, ah, so you find your brother and the brother came, this is the last thing to do yourself. But you do not know your brother has received a gift, you just concentrate on getting the job done.

  Along the way think, if this in itself is no class implements an interface it, how you disguise me, I would even think of this opportunity to let you come up with twin brother, then use the first two kinds proxy mode, create a target class subclass birth to a son, her son pretend I

  (2) generate a subclass call , this time with a subclass of class masquerading as do, of course, this also can escape the JVM's strong type checking, I inherited it, of course, check out the subclass overrides the target class all methods, of course, in these methods to rewrite, not only to achieve the function of the target class, also before these functions to achieve a number of other (written logs, security checks, and other things).

  The contrast is, starting with my father that his son learned the skill all, everyone looking for his son to do things, but every time his son to do the same thing before and father, should receive a small gift (write journal) before running a real thing. Of course, my father did not know his son is so dry up. Here there are things to say, some skill is unique Dad (final), the son can not learn, can not learn things you can not do this, can not do this thing, people naturally can not accept a gift.

The former brothers mode, spring will use the JDK java.lang.reflect.Proxy class, which allows Spring dynamically generates a new class that implements the necessary interfaces, weaving notice, and to any calls to these interfaces are forwarded to the target class.

The latter model father and son, spring CGLIB libraries generated using a subclass of the target class, creating a subclass of this time, spring woven into notice, and the calls to the subclass delegate to the target class.

In contrast, the brothers mode or better, he can better achieve loose coupling, especially in the case of today are shouting interface-oriented programming model father and son but in the absence of implementation of the interface can also be woven into the notice, should make an exception.

7, cglib (Enhanced byte code)

 ① no interface, only the implementation class ; ② using bytecode CGLIB frame, creating a subclass of the target class at run-time, thereby enhancing the target classes. ③ introducing carrier package: the core package \ lib \ bytecode \ cglib \ cglib -2.2.jar hibernate-distribution-3.6.10.Final dependent packages and struts-2.3.15.3 \ apps \ struts2- blank \ WEB-INF \ lib \ asm -3.3.jar

spring-core.jar has integrated the above two packages.

8, AOP Alliance

    ① Pre-notification (Before Advice): implement an enhanced method of performing in front of goal.  Advice executed before the connection point, but unless it throws an exception, otherwise there is no ability to interrupt the flow of execution. Use  @Before annotations using this Advice.

    ② post notice (After Advice): implement an enhanced executed after the target method.  Whether the connection point is by what means to exit (return to normal or throw an exception) will be executed at the end of the implementation of these Advice. By  @After annotation use.

    ③ surround notification (Around Advice): the target method is performed, before and after the implementation of enhanced . Advice connection points around the implementation of a method call on you. This is the most powerful of Advice. By  @Aroundannotation use.

    ④ notification exception is thrown (AfterThrowing Advice): implement an enhanced after method throws an exception . If a way to exit by throwing an exception, then this Advice will be executed. General  @AfterThrowing notes to use.

9、AspectJ

      ① It is a java-based AOP framework language ; ② Java-compatible platform that can seamlessly expand. spring2.0 later adds support for the cut point expression. easy to use. @AspectJ is AspectJ1.5 new features, by JDK5 annotation technique allows to define cut directly in the Bean class. (New version of Spring recommended way to develop AspectJ AOP, the main purposes: custom development)

      Spring Aop and the difference AspectJ: Dynamic Spring Aop used in weaving, and the weaving Aspectj static. Static weaving: refers to weaving at compile time, namely: translation of the class file byte code has been woven into. The weaving is divided into two kinds of static and dynamic, static refers to the weaving process is performed only at the first call; moving the finger to determine how, when each call is executed in accordance with Target status code intermediate dynamic operation.

10, the cut-point expression

      Syntax: execution (Modifier class method returns the value package name (parameter) throws exception.)

                 execution(* com.nic.* .*(..))

      Modifiers: General omitted

     * Represents all first return type: can not be omitted. represents the return value is not void, String represents a String, * denotes an arbitrary value

     Package: com.nic fixed packet

      The second * for all classes

      * The third class on behalf of all methods

     Finally, a representative of all the parameters ..

11 JdbcTemplate

(1) Introduction: ①JdbcTemplate DbUtils similar to the human, for operating the tool Jdbc class, it needs to rely on a connection pool, the DataSource (data source); ②JDBC (the DataBase Connectivity Java, Java Database Connectivity ) is a used to execute SQL statements the API java ; ③ODBC ( the open database Connectivity ) open database Connectivity, a standard database access API set provided by Microsoft Corporation of open (application programming Interface) (commonly used in SQLserver); ④DBCP (dataBase connection pool ) database connection pool, the java a connector pool database, developed by the Apache ; ⑤ C3P0 is an open source JDBC connection pool, which implements the data source and JNDI bindings that support the specification and JDBC3 JDBC2 standard extension. It currently use open source project Hibernate, spring and so on.

The difference (2) C3P0 and dbcp of: ① dbcp not automatically reclaim free connection function , C3P0 there; ② mainly two different ways of handling data connection! C3P0 maximum idle time, the DBCP maximum number of connections ; ③ When connecting the former exceeds the maximum idle time of connection, the current connection will be broken. When DBCP when the number of connections exceeds the maximum number of connections, all connections are disconnected ; ④ DBCP Its principle is to maintain multiple connection object Connection, a web project to connect directly use the object it maintains the database connection, eliminating the need for each You must create trouble connecting object. Improve efficiency and reduce memory usage. s3p0 can automatically recover connection, DBCP need to manually release resources to return. But dbcp more efficient.

 (3) introduced into the carrier package: ①com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar (the c3p0 connection pool) /

1.2.2.osgi.jar-com.springsource.org.apache.commons.dbcp, com.springsource.org.apache.commons.pool-1.5.3jar (dbcp the c3p0 connection pools and connection pool to select a line to import); ②mysql-connector-java-5.0.8- bin.jar (mysql drive), ③spring-jdbc-3.2.0.RELEASE.jar; ④spring-tx-3.2.0.RELEASE.jar ( transaction).

(4) simple application JdbcTemplate

①model layer

package com.gfy.model;

public class User {

	private Integer id;
	private String username;
	private String password;
	
	public Integer getId() {
		return id;
	}
	
	public void setId(Integer id) {
		this.id = id;
	}
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	
	
}

② to create the database:

③test layer

package com.gfy.test;

import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;

public class lesson04 {

	 @Test
		public void test() throws Exception {
	   //创建数据源
		 BasicDataSource dataSource=new BasicDataSource();
		 dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		 dataSource.setUrl("jdbc:mysql:///spring_day04");// 其中的///代表本地,spring_day04表示你的数据库中的表名字
		 dataSource.setUsername("root");//root表示你的数据库的登录名
		 dataSource.setPassword("123456");//123456表示你你的数据库的登录密码
	    //创建JdbcTemplate
		
		 JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
		jdbcTemplate.update("update t_user set username =? where id=?","aa",1);//表示将id=1的username修改为zzz
		 System.out.println("成功更新!");
		
	}
}

 result:

(5) the data source is arranged spring

①dao layer: Interface

package com.gfy.dao;

import com.gfy.model.User;

public interface IUserDao {
       public void add(User user);
      
}

Implementing Classes:

package com.gfy.dao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import com.gfy.model.User;
@Repository      //Dao层
public class UserDaoImpl2  implements IUserDao {
	private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	@Override
	public void add(User user) {
		System.out.println("Dao添加用户"+user);
       jdbcTemplate.update("insert t_user (username,password) values(?,?) ",user.getUsername(),user.getPassword());
	}
}

②model layer

package com.gfy.model;
public class User {
	private Integer id;
	private String username;
	private String password;	
	public Integer getId() {
		return id;
	}	
	public void setId(Integer id) {
		this.id = id;
	}	
	public String getUsername() {
		return username;
	}	
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}	
}

③web layer, xml configuration

<?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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        https://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context
                        https://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/aop
                        https://www.springframework.org/schema/aop/spring-aop.xsd">
      
     <!-- 配置DBCP dataSource对象 -->
     <!--  BasicDataSource dataSource=new BasicDataSource();
		 dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		 dataSource.setUrl("jdbc:mysql:///spring_day04");// 其中的///代表本地
		 dataSource.setUsername("root");
		 dataSource.setPassword("123456"); -->
     <!--   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql:///spring_day04" />
      <property name="username" value="root" />
      <property name="password" value="123456" />
     </bean> 
     --> 
     <!-- 配置C3P0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
          <property name="driverClass" value="com.mysql.jdbc.Driver" />
           <property name="jdbcUrl" value="jdbc:mysql:///spring_day04" />
            <property name="user" value="root" />
             <property name="password" value="123456" />
     </bean>
     
     <!-- 配置jdbcTemplate对象 -->
      
     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
     </bean> 
    <!-- 配置Dao -->
    <bean id="userDao" class="com.gfy.dao.UserDaoImpl">
       <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
</beans>

④test layer

package com.gfy.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.gfy.dao.IUserDao;
import com.gfy.model.User;
public class lesson05 {
	 @Test
		public void test() throws Exception {
	   /*
		 //创建数据源
		  * 
		 BasicDataSource dataSource=new BasicDataSource();
		 dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		 dataSource.setUrl("jdbc:mysql:///spring_day04");// 其中的///代表本地
		 dataSource.setUsername("root");
		 dataSource.setPassword("123456");
	    //创建JdbcTemplate
		 JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
		jdbcTemplate.update("update t_user set username ? where id=?","zzz",1);
	*/
		ApplicationContext context=new ClassPathXmlApplicationContext("beans05.xml"); 
		IUserDao userDao=(IUserDao) context.getBean("userDao");
		 User user=new User();
		 user.setUsername("gfrfy");
		 user.setPassword("123657");
		 userDao.add(user);
	 }
}

(6)用JdbcDaoSupport简化JdbcTemplate和配置db.properties(数据库已存在)

       把数据库的连接信息配置到一个独立的文件中;在src[类路径]写个db.properties文件,然后在xml中配置读取db.properties文件信息。

配置db.properties

driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql:///spring_day04
user=root
password=123456

②model层

package com.gfy.model;

public class User {
	private Integer id;
	private String username;
	private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

③dao层:接口

package com.gfy.dao;

import com.gfy.model.User;

public interface IUserDao {
       public void add(User user);
      
}

实现类:

package com.gfy.dao;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import com.gfy.model.User;
@Repository      //Dao层
public class UserDaoImpl extends JdbcDaoSupport  implements IUserDao {
	@Override
	public void add(User user) {
		System.out.println("Dao添加用户"+user);
       getJdbcTemplate().update("insert t_user (username,password) values(?,?) ",user.getUsername(),user.getPassword());
	}
}

④web层,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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        https://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context
                        https://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/aop
                        https://www.springframework.org/schema/aop/spring-aop.xsd">
      
     <!-- 配置DBCP dataSource对象 -->
     <!--  BasicDataSource dataSource=new BasicDataSource();
		 dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		 dataSource.setUrl("jdbc:mysql:///spring_day04");// 其中的///代表本地
		 dataSource.setUsername("root");
		 dataSource.setPassword("123456"); -->
     <!--   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql:///spring_day04" />
      <property name="username" value="root" />
      <property name="password" value="123456" />
     </bean> 
     --> 
     <!-- 读取db.properties文件 -->
     <context:property-placeholder location="classpath:db.properties"/>
     <!-- 配置C3P0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
          <property name="driverClass" value="${driverClass}" />
           <property name="jdbcUrl" value="${jdbcUrl}" />
            <property name="user" value="${user}" />
             <property name="password" value="${password}" />
     </bean>
     
     <!-- 配置jdbcTemplate对象 -->
      <!-- 
     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
     </bean>  -->
    <!-- 配置Dao -->
    <bean id="userDao" class="com.gfy.dao.UserDaoImpl">
      <!--   <property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
      <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    
</beans>

⑤test层

package com.gfy.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.gfy.dao.IUserDao;
import com.gfy.model.User;
public class lesson06 {

	 @Test
		public void test() throws Exception {

		ApplicationContext context=new ClassPathXmlApplicationContext("beans06.xml"); 
		IUserDao userDao=(IUserDao) context.getBean("userDao");
		 User user=new User();
		 user.setUsername("xiaomi");
		 user.setPassword("16700");
		 userDao.add(user);
		 System.out.println("成功插入用户!");
		
	 }
}

 

 

 

发布了57 篇原创文章 · 获赞 36 · 访问量 6万+

Guess you like

Origin blog.csdn.net/hqy1719239337/article/details/97900975