org.springframework.context.annotation.ImportSelector用法(简单模拟springAop(学习记录))

ps:注意依赖

		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>

自定义标签

import org.springframework.context.annotation.Import;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Import(ApoPostUtil.class)
public @interface EnableMy {
}

测试接口

public interface Dao {
    public void query();
}

测试实现类

import org.springframework.stereotype.Component;

@Component
public class IndexDao implements Dao{
    public void query(){
        System.out.println("dao");
    }
}

模拟Aop

public class ApoPostUtil implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("indexDao")){
            //动态代理对象
            bean = Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{Dao.class},new MyInvocationHandler(bean));
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }
}

selectImports方法

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{ApoPostUtil.class.getName()};
    }
}

动态代理实现类

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

public class MyInvocationHandler implements InvocationHandler {
    Object target;
    public MyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Proxy方法");
        return method.invoke(target,args);
    }
}

配置文件类

@ComponentScan("com.luban")
@EnableMy
public class Appconfig {
//    @Bean
//    public IndexDao1 indexDao1(){
//        return new IndexDao1();
//    }
}

方法调用Test类

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext =
                new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(Appconfig.class);
        annotationConfigApplicationContext.refresh();
        //代理对象
        Dao dao = (Dao) annotationConfigApplicationContext.getBean("indexDao");
        dao.query();
    }
}

你可能感兴趣的:(org.springframework.context.annotation.ImportSelector用法(简单模拟springAop(学习记录)))