Spring_IoC annotations and XML developers to develop the AOP (study notes 2)

A: IoC annotations development

1, need to be introduced in the context constraints applicationContext.xml

<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"> <!-- bean definitions here --> </beans>

2, simple annotation Development Example

  <!-- 进行IoC注解开发,首先在配置文件里配置组件扫描,即哪个包下的类进行注解开发 -->  
	<context:component-scan base-package="com.test.spring.demo1"/>
@Component("userDao")
public class UserDaoImp implements UserDao { @Value("三八") private String name; @Override public void save() { System.out.println("UserDaoImp的save方法执行了"+name); } } 

Note: For injection property to be achieved in a class, may not be provided the method attribute set, if provided, the hair can be applied @Value annotations in the set method

3, IoC annotations details

@Component 

Modification of a class, the class will be handed over to Spring management, there are three derivative annotation (similar function) is recommended with three notes derived

  1. @Controller (web layer)
  2. @Service (service layer)
  3. @Repository (dao layer)
@Repository("userDao")
public class UserDaoImp implements UserDao { @Value("三八") private String name; @Override public void save() { System.out.println("UserDaoImp的save方法执行了"+name); } } 

Properties injected comment

  • @Value ( "") injection common attributes, and attribute values ​​set
  • @Autowired injection object properties, injection according to the type of object, but is generally injected by name, with annotations need @Qualifier (value = "Name" 
  • @Resource (name = "name") into the object properties by name, common
@Service("userService")
public class UserServiceImp implements UserService { //注入UserDao /*@Autowired @Qualifier(value="userDao")*/ @Resource(name="userDao") private UserDao userDao; @Override public void save() { System.out.println("UserService的save方法执行了"); userDao.save(); } } 

Other notes:

  • @PostConstruct initialization method
  • @PreDestroy destruction method
  • @Scope ( "singleton & prototype & request & session & globalsession") annotation scope, the default is singleton, singleton
@Service("customerService")
@Scope
public class CustomerServiceImp implements CustomerService { @PostConstruct public void Init(){ System.out.println("init"); } @Override public void save() { } @PreDestroy public void Destroy(){ System.out.println("destroy"); } }

4, xml and notes the difference between integration and development

Annotations and XML configuration differences

Note: metadata in a distributed, tightly bound with the source code.

xml: is a centralized meta data, with the source code without binding.

Details: https://www.cnblogs.com/iOS-mt/p/6133656.html

xml development and integration of annotation (understand)

Note: bean managed to xml, property injection to comment

<bean id="customerService" class="com.test.spring.demo2.CustomerServiceImp"/> <bean id="productDao" class="com.test.spring.demo2.ProductDao"/> <!-- 需要开启以下配置,在没有扫描的情况下,能够使用注解将属性注入 @Value @Resource @Autowired @Qualifier--> <context:annotation-config />

 Two, AOP (Aspect Oriented Programming) Oriented Programming

Reference: http://www.cnblogs.com/xrq730/p/4919025.html

AOP is a simple illustration:

1, the underlying principle of dynamic proxies (reflection)

  • JDK dynamic proxy: Only class that implements the interface proxy
  • Cglib :( dynamic proxy class is the third party agent to Javasist technology) can be achieved without the agent to the implementation of the interface class, subclass object generated
//Cglib动态代理简单实现,增强UserDao中的save方法
public class UserDaoProxy implements MethodInterceptor{ private UserDao userDao; public UserDaoProxy(UserDao userDao) { super(); this.userDao = userDao; } public UserDao createProxy(){ //1,获取Cglib动态代理核心类 Enhancer enhancer=new Enhancer(); //2,设置父类 enhancer.setSuperclass(userDao.getClass()); //3,设置回调:(类似于 InvocationHandler对象) enhancer.setCallback(this); //4,创建代理对象 UserDao proxy = (UserDao) enhancer.create(); return proxy; } @Override public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { if("save".equals(method.getName())){ System.out.println("增强代码"); return methodProxy.invokeSuper(proxy, args); } return methodProxy.invokeSuper(proxy, args); } } 

2, AOP related terms:

  • JoinPoint (point of attachment, may be enhanced / are cut method may be referred to the point of attachment)
  • Pointcut (entry point, the real point is enhanced connectivity is known as the starting point)
  • The Advice (notification / enhancement, enhancement of the relevant code or method)
  • Introduction (introducing, enhanced class level, ie directly into the enhanced class code)
  • Target (target, the enhanced object)
  • Weaving (weaving, the Advice of Target into the process)
  • The Proxy (proxy, after class by weaving AOP)
  • Aspect (combination section, a plurality of notifications, and a plurality of entry points)

Note: a single entry point may be a single method of a class in the packet, the method may be a plurality of classes of a plurality of one or more packages, flexible configuration required

 

3, based on xml aspectJ aop development of simple entry

1) into the corresponding jar package

2) introducing the aop schema constraints in the configuration file

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here --> </beans>

3) the preparation of the target class

public class ProductDaoImp implements ProductDao { @Override public void save() { System.out.println("product保存"); } @Override public void delete() { System.out.println("product删除"); } } 

4) writing class section

public class MyAspectXml {
	public void checkPriviledge(){ System.out.println("权限校验代码========="); } } 

5) xml configuration

        <!-- 配置目标对象 -->
	<bean id="productDao" class="com.test.demo1.ProductDaoImp"></bean> <!-- 配置切面类 --> <bean id="myAspect" class="com.test.demo1.MyAspectXml"></bean> <!-- 配置AOP对目标对象产生代理 --> <aop:config> <!-- 配置切入点 --> <aop:pointcut expression="execution(* com.test.demo1.ProductDaoImp.save(..))" id="pointcut1" /> <!-- 配置切面 --> <aop:aspect ref="myAspect"> <aop:before method="checkPriviledge" pointcut-ref="pointcut1" /> </aop:aspect> </aop:config>

4, advice (notification) Type

1) Pre-notification

Only get to the entry point information (of all types of notifications can be obtained)

public class MyAspectXml {
	public void checkPriviledge(JoinPoint joinpoint){ System.out.println("权限校验代码========="+joinpoint); } }

2) after advice

You can obtain the entry point of the return value

public void writeLog(Object obj){ System.out.println("日志代码========="+obj); }
<!-- 后置通知 -->
<aop:after-returning method="writeLog" pointcut-ref="pointcut2" returning="obj"/> 

3) around advice

Both before and after the starting point of the enhanced implementation of the relevant code, you can prevent the execution of an entry point (such as an entry point for transaction processing)

public void round(ProceedingJoinPoint joinPoint) throws Throwable{ System.out.println("环绕前代码========"); //执行切入点的方法 joinPoint.proceed(); System.out.println("环绕后代码========"); }
 <!-- 环绕通知 -->
<aop:around method="round" pointcut-ref="pointcut3"/> 

4) exception notification

When the entry point for the application / notification of abnormal operation, will perform exception notification, you can throw an exception

public void afterThrowing(Throwable ex){ System.out.println("异常抛出通知代码====="+ex.getMessage()); }
  <!-- 异常通知 -->
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut4" throwing="ex"/> 

5) The final notice

Regardless of whether there is an exception entry point, the code will eventually notice of execution

 <!-- 最终通知 -->
<aop:after method="after" pointcut-ref="pointcut4"/>

5, pointcut expression

Execution ([Access Modifiers] Access Return Value Type package name. class name. Method name (parameter))

Access modifier can be omitted, can be used to access return type instead of *, represents any type, instead of the parameter .., * represents an arbitrary parameter can be flexibly configured with a starting point

Example: Say in all classes * * * * (..) represents any packets are configured as an entry point method

        * Com.test.dao.UserDao + .save (..) represents UserDao class and its subclasses save method configured as an entry point

Guess you like

Origin www.cnblogs.com/wuba/p/11028437.html