1、测试类接口
package com.fh.imports.dao; public interface TestDao { void test(); }
测试类实现
package com.fh.imports.dao; import org.springframework.stereotype.Component; @Component(value = "testDao") public class TestDaoImpl implements TestDao { @Override public void test() { System.out.println("TestDaoImpl"); } }
2、添加一个ImportSelector的实现类
package com.fh.imports; import com.fh.imports.dao.TestDaoImpl3; 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[]{TestDaoImpl3.class.getName()}; } }
3、添加上面的TestDaoImpl3这个类
package com.fh.imports.dao; import com.fh.imports.ProxyInvocationHandler; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import java.lang.reflect.Proxy; public class TestDaoImpl3 implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if("testDao".equals(beanName)){ bean = Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{TestDao.class},new ProxyInvocationHandler(bean)); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return null; } }
4、添加对应的InvocationHandler类
package com.fh.imports; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class ProxyInvocationHandler implements InvocationHandler { Object target; public ProxyInvocationHandler(Object object){ this.target = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("代理类执行!!!"); return method.invoke(target,args); } }
5、添加注解类导入
package com.fh.imports; import org.springframework.context.annotation.Import; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(MyImportSelector.class) public @interface EnableProxy { }
6、添加一个配置类,进行注解配置即可
package com.fh.imports; import org.springframework.context.annotation.Configuration; @Configuration @EnableProxy public class ImportConfig { // @Bean // public TestDao getTest(){ // return new TestDaoImpl(); // } }
7、最后添加测试类,从容器中获取相关的实例,查看是否被代理
TestDao testDao = (TestDao) context.getBean("testDao"); testDao.test();
最后,项目的目录结构:
完