@Retention ( RetentionPolicy. RUNTIME)
@Import ( MyImportSelector. class )
public @interface EnableLuban {
}
@ComponentScan ( "com.luban" )
@EnableLuban
public class Appconfig {
@Bean
public IndexDao indexDao ( ) {
return new IndexDao ( ) ;
}
}
public interface Dao {
public void query ( ) ;
}
public class IndexDao implements Dao {
@Override
public void query ( ) {
System. out. println ( "indexDao" ) ;
}
}
public class IndexDao3 implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization ( Object bean, String beanName) throws BeansException {
if ( beanName. equals ( "indexDao" ) ) {
bean = Proxy. newProxyInstance ( bean. getClass ( ) . getClassLoader ( ) , new Class [ ] { Dao. class } , new MyInvocationHandler ( bean) ) ;
}
return bean;
}
@Override
public Object postProcessAfterInitialization ( Object bean, String beanName) throws BeansException {
return null;
}
}
public class MyImportSelector implements ImportSelector {
@Override
public String[ ] selectImports ( AnnotationMetadata importingClassMetadata) {
return new String [ ] { IndexDao3. class . getName ( ) } ;
}
}
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 ( "我是代理方法" ) ;
return method. invoke ( target, args) ;
}
}
public class test {
public static void main ( String[ ] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext =
new AnnotationConfigApplicationContext ( Appconfig. class ) ;
Dao dao = ( Dao) annotationConfigApplicationContext. getBean ( "indexDao" ) ;
dao. query ( ) ;
}
}