首页 > 解决方案 > 使用BeanPostProcessor创建代理,但peoxy类字段为空

问题描述

有服务

@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;
}

}

这是方法拦截器

public class MyMethodInterceptor implements MethodInterceptor {

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

这是控制器

@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 字段不为空,所以 reson 与 BeanPostProcessor 有关。

谁能帮我

标签: javaspringspring-bootproxy

解决方案


推荐阅读