被aop增强的类:
接口
public interface IUserService {
void findUserById(int id);
}
实现类:
@Service
@Setter
public class UserServiceImpl implements IUserService{
@Override
public void findUserById(int id) {
System.out.println("找到一个用户");
}
}
aop切面
@Component
@Aspect
public class AopAdvice {
@Before("execution(* com.idea.spring.service.Impl.UserServiceImpl.*(..))")
public void before() {
System.out.println("---------方法执行前before()---------");
}
}
通过getBean()进行调用时出现报错如下:
No qualifying bean of type ‘com.idea.spring.service.Impl.UserServiceImpl’ available
经过百度什么的查看发现应该是aop切面插入后该bean被jdk内部自动转为了com.sun.proxy.$Proxy25类型类型已被转变,所以无法通过类UserServiceImpl进行获取
经测试发现可以通过接口IUserService或byName获取
获取后如何执行该类的方法呢?
经过一段思考后发现可以用反射来实现
@Test
public void testService() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
Object userService = applicationContext.getBean(IUserService.class);
Method method = userService.getClass().getMethod("findUserById", int.class);
method.invoke(userService,1);
}
该问题终于得到了解决。。。。。。。。。。。。。。。。。