我需要从接口拦截方法,并找到了 MethodInterceptor 的这个实现,我在一个新的 spring 应用程序上进行了测试并工作了。
问题是,我似乎无法让它在我需要的 spring 应用程序上运行。
@Configuration
public class TestMethodConfig {
@Autowired
private TestService testService;
@Bean
@Primary
public ProxyFactoryBean testProxyFactoryBean() {
ProxyFactoryBean testProxyFactoryBean = new ProxyFactoryBean();
testProxyFactoryBean.setTarget(testService);
testProxyFactoryBean.setInterceptorNames("testMethodInterceptor");
return testProxyFactoryBean;
}
}
@Service
public class TestServiceImpl implements TestService{
@Override
public void testMethod(String test) {
System.out.println("testService String");
}
}
public interface TestService{
void testMethod(String test);
}
@RestController
public class Controller {
@Autowired
private TestService testProxyFactoryBean;
@GetMapping(value = "/test")
public void test(){
testProxyFactoryBean.testMethod("valor");
}
}
@Component
public class TestMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("before method");
System.out.println("invocation: " + Arrays.toString(invocation.getArguments()));
Object retVal = invocation.proceed();
System.out.println("after method");
return retVal;
}
}
我使用Spring Actuator检查bean关系,我发现Controller上的@Autowired TestService应该被分配给testProxyFactoryBean,但它被分配给TestServiceImpl bean,所以我相信创建代理有问题。