About realization of the principle of the Spring Aop and Ioc

1.AOP
the AOP (Aspect Oriented) is a programming paradigm, there is provided a program from another point of view to improve the structure of object-oriented programming (OOP).
AOP provides a mechanism for developers described crosscutting concerns, and automatically crosscutting concerns woven into object-oriented software system, enabling a modular crosscutting concerns.
AOP can be independent of those services, but for the service module logic or liability common call, such as transaction processing, log management, access control, etc., encapsulated, easy to reuse the code reduction system, to reduce the coupling between modules, and have conducive to the future operability and maintainability.

The benefits of using AOP

Reduction module coupling degree
to make the system easy expansion
to improve code reusability
basic concept of AOP

Connection point (JoinPoint): in the program needs to be inserted transverse to the focus point, the point of attachment may be in the class initialization, method calls, exception processing, or the like field called. Spring only supports method execution join point.
A set of group related connection point: pointcut (Pointcut).
Notification (Advice): acts performed at the connection point, the connection point is provided to enhance the AOP in the selected entry point requires a means to extend an existing behavior. Comprises a pre-enhancement (before advice), reinforcing post (after advice), surround enhancement (around advice).
Section (Aspect): combination of notifications and entry points.
Weaving (Weaving): weaving is a process that is applied to the target object is cut out to create AOP proxy object of the process.
Proxy (Proxy): to apply the section of the target object through a proxy way. AOP proxy can be achieved using JDK dynamic proxy or proxy CGLIB.
Audience (Target): attention needs to be woven into the target point. Ie proxy objects.

AOP to achieve the main design model is dynamic proxy.
Spring dynamic proxy, there are two: First, JDK dynamic proxy; the other is cglib dynamic proxy.

JDK dynamic proxy analog
JDK dynamic proxy interfaces of two core (s) and are InvocationHandler Proxy. Note: Only the agent interface.

public class TimeHandler implements InvocationHandler {

// 目标对象  
private Object targetObject;  

public TimeHandler(Object targetObject){
      this.targetObject = targetObject;
}
@Override  
//关联的这个实现类的方法被调用时将被执行  
/*InvocationHandler接口的方法,proxy表示代理,method表示原对象被调用的方法,      
    args表示方法的参数*/  
public Object invoke(Object proxy, Method method, Object[] args)  
        throws Throwable {  
    Object ret=null;  
    try{  
        System.out.println("方法之前:"+System.currentTimeMillis());    
        //调用目标方法  
        ret=method.invoke(targetObject, args);  
        System.out.println("方法之后:"+System.currentTimeMillis());  
    }catch(Exception e){  
        e.printStackTrace();  
        System.out.println("error");  
        throw e;  
    }  
    return ret;  
}  

}
TimeHandler InvocationHandler class implements the interface. To achieve the core method invoke, a total of three parameters. The first parameter generated proxy class instance, the second parameter of the target object method, an array of parameter values of the third parameter method.

public class ProxyUtil {

@SuppressWarnings("unchecked")
public static <T> T proxyOne(ClassLoader loader,Class<?>[] clz,InvocationHandler handler){
    return (T)Proxy.newProxyInstance(loader, clz, handler);
}

}
ProxyUtil simple class encapsulates at the Proxy.newProxyInstance () method. This method also has three parameters. The first parameter to generate a proxy object class loader, a second array of interfaces of the target object parameter, the third parameter is the class instance InvocationHandler interface.

public interface UserManager {
public void addUser(String userId, String userName);
}
public class UserManagerImpl implements UserManager {
@Override
public void addUser(String userId, String userName) {
System.out.println(“addUser(id:”+userId+",name:"+userName+")");
}

}
public static void main(String[] args) {
UserManager um=new UserManagerImpl();
LogHandler log =new LogHandler(um);
um=ProxyUtil.proxyOne(um.getClass().getClassLoader(),
um.getClass().getInterfaces(), log);

   TimeHandler time = new TimeHandler(um);
   um=ProxyUtil.proxyOne(um.getClass().getClassLoader(), 
             um.getClass().getInterfaces(), time);
     
     um.addUser("1111", "张三");
}

To demonstrate need, here we added a LogHandler, like TimeHandler code.

Simulation of dynamic proxy CGLIB
CGLIB dynamic proxy interfaces of two core (s) are MethodInterceptor and Enhancer. It is not very similar to JDK dynamic proxy, the use of the same. But CGLIB can proxy classes and interfaces. Note: You can not proxy final class.

public class TimeInterceptor implements MethodInterceptor {
private Object target;
public TimeInterceptor(Object target) {
this.target = target;
}
@Override
public Object intercept(Object proxy, Method method,
Object[] args, MethodProxy invocation) throws Throwable {
System.out.println(“方法之前:”+System.currentTimeMillis());
Object ret = invocation.invoke(target, args);
System.out.println(“方法之后:”+System.currentTimeMillis());

    return ret;
}

}
Intercept Method 4 parameters. 1. Examples of the generated proxy class. 2. referenced proxy object. 3. The method, the value array. 4. The proxy class references to proxy approach.

public class ProxyUtil {
@SuppressWarnings(“unchecked”)
public static T proxyOne(Class<?> clz,MethodInterceptor interceptor){
return (T)Enhancer.create(clz, interceptor);
}

}
Enhancer enhancer class bytecode in CGLib.

public class UserManage {
public void addUser(String userId, String userName) {
System.out.println(“addUser(id:”+userId+",name:"+userName+")");
}
}

static void main public (String [] args) {
UserManage UserManage new new UM = ();
TimeInterceptor new new TimeInterceptor Time = (UM);
UM = ProxyUtil.proxyOne (um.getClass (), Time);
um.addUser ( "111" "Wang");
}
2.IOC
the IOC (inversion control)] a code is dependent on the design ideas inversion principle. The object is to the original code which need to be implemented to create dependencies between objects, reverse to the container to help achieve.
Spring IOC container by dependencies between xml, annotations and other classes and arranged to complete the creation and management of the injection dependency object. IOC to achieve the main design pattern is the factory pattern.

The benefits of using IOC's
centralized management, implementation class configurable and easy to manage.
Reducing the degree of coupling between the class and class.
IOC simple simulation

public interface BeanFactory {
Object getBean(String id);
}

the ClassPathXmlApplicationContext the implements the BeanFactory class {public
// container, used to store the injected Bean
Private the Map <String, Object> = new new Container the HashMap <String, Object> ();

//解析xml文件,通过反射将配置的bean放到container中  
public ClassPathXmlApplicationContext(String fileName) throws Exception{  
    SAXBuilder sb = new SAXBuilder(); 

    Document doc 
    =sb.build(ClassPathXmlApplicationContext.class.getResource("/"+fileName));
   
    Element root = doc.getRootElement();  
    List<Element> list = XPath.selectNodes(root, "/beans/bean");  

    for (int i = 0; i < list.size(); i++) {              
       Element bean = list.get(i);  
       String id = bean.getAttributeValue("id");  
       String clazz = bean.getAttributeValue("class");  
       Object o = Class.forName(clazz).newInstance();  
       container.put(id, o);  
      }  
}
@Override  
public Object getBean(String id) {        
    return container.get(id);  
}  

}
Need to import jdom.jar package.

<?xml version="1.0" encoding="UTF-8"?> public interface Animal { void say(); }

public class Dog implements Animal {
@Override
public void say() {
System.out.println(“汪汪”);
}
}
public class Chicken implements Animal {
@Override
public void say() {
System.out.println(“鸡你很美”);
}
}
public class People {
public void info(){
System.out.println(“小明-23岁”);
}
}

public static void main(String[] args) throws Exception {

    //加载配置文件  
    BeanFactory f = new ClassPathXmlApplicationContext("applicationContext.xml");  

    Object os = f.getBean("dog");  
    Animal dog = (Animal)os;  
    dog.say();  

    Object op = f.getBean("chicken");  
    Animal chicken = (Animal)op;  
    chicken.say();  

    Object p = f.getBean("people");  
    People people= (Animal)p;  
    people.info();  
} 

There are a number of possible write more user-friendly reference

Released five original articles · won praise 17 · views 365

Guess you like

Origin blog.csdn.net/sublime_k/article/details/104267013