IOC全注解和JDK动态代理实现

发布于 2021-08-25  58 次阅读


1.dao和实现类

package com.apesblog.dao;

public interface UserDao {

    int add(int a,int b);
    int multiply(int a,int b);

}
package com.apesblog.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {

    @Override
    public int multiply(int a, int b) {
        return a * b;
    }

    @Override
    public int add(int a, int b) {
        return a + b;
    }
}

2.MyInvocationHandler

package com.apesblog.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

@Component
public class MyInvocationHandler implements InvocationHandler {
    @Autowired
    UserDao userDao;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("----------");
        Object invoke = method.invoke(userDao, args);
        System.out.println(invoke);
        System.out.println("----------");
        return invoke;

    }
}

3.@Configuration或者xml

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"com.apesblog"})
public class SpringConfig {

}
<?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="com.apesblog"></context:component-scan>

</beans>

4.测试类


import com.apesblog.dao.MyInvocationHandler;
import com.apesblog.dao.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.lang.reflect.Proxy;

public class Test1 {

    public static void main(String[] args) {
        //xml
//        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
        //全注解
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);

        MyInvocationHandler myInvocationHandler = (MyInvocationHandler) applicationContext.getBean("myInvocationHandler");
        Class[] interfaces = {UserDao.class};
        UserDao o = (UserDao) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), interfaces, myInvocationHandler);
        o.add(1, 2);
        o.multiply(1, 2);

    }
}