使用BeanPostProcessor创建代理,但peoxy类字段为空

service

@Service
public class TestService {
    public void test(){
        System.out.println("test");
    }
}

BeanPostProcessor

@Component
public class Demo2 implements BeanPostProcessor {

    Enhancer enhancer=new Enhancer();

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

    Class clazz=bean.getClass();
    Annotation annotation=clazz.getAnnotation(HttpAnnotion.class);
    if(annotation!=null){

        if(clazz.isInterface()){
            throw new BeanCreationException("can not use for interface");
        }
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(new MyMethodInterceptor());
        Object proxy =enhancer.create();
        return proxy;
    }
    return bean;
}

MethodInterceptor

public class MyMethodInterceptor implements MethodInterceptor {

   @Override
   public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
       return proxy.invokeSuper(obj,args);
   }
}

controller

@RestController
@RequestMapping("/test")
@Slf4j
@HttpAnnotion
public class HelloController {

    @Autowired
    private TestService testService;

    @PostMapping
    public void tran(@RequestBody JSONObject j){
        System.out.println("aaa");
    }
}

当控制器接收到请求时,testService字段为空。

我测试发现,在BeanPostProcessor中,在创建代理之前,Bean的testService字段不是空的,在创建代理之后,该字段变成空的。

我试着不通过BeanPostProcessor来创建代理,TestService字段也不是空的,所以故障与BeanPostProcessor有关。

谁能帮助我?


StackOverflow:https://stackoverflow.com/questions/68143510/use-beanpostprocessor-to-create-proxy-but-the-peoxy-class-field-is-null