springMVC中controller层方法中使用private和public问题

楼主一直习惯使用public,偶尔手误也可能使用private,但是发觉也没啥区别,都能调用service层,注入bean。

      后来做一个新项目时,发觉自己以前的写的部分功能报错,当时有点懵逼,,找了半天都没发现哪里写错了,代码啥的都确定无错(这种时候最蛋疼,因为报错不太准确),以前写好的啥都没改,突然报错,经过蛋疼的排除,发现service层的注入都是null,但是还是一脸懵逼,我一直以为无区别,感觉自己的代码无错,经过长时间找寻(我感觉自己快要崩溃了),然后发现自己另一个类有相似的方法,就用的实体类不要样当然还有一个用public一个用private,经过测试才发现用public的方法,调用controller里面注入类才能注入。但是为什么会这样呢?为什么以前好好的,突然不可以了呢?

原因分析:

容器扫描bean生成代理类的时候,public和protected方法可以被正常代理,而private方法的不会被代理,属性的注入也是在代理类中完成,所以public/protected方法获取的注入属性是完成注入的属性,private方法获取的是未完成注入时的属性,所以是null。

原来是我们老大在项目加AOP,加了AOP以后会有影响,如果controller层方法需要调用注入的bean或者service层,那么只能使用public。

转载于:https://www.cnblogs.com/loong-hon/p/11308514.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用CGLIB代理计算方法耗时的步骤如下: 1. 引入cglib和asm的依赖。 2. 创建一个实现MethodInterceptor接口的拦截器类,重写intercept方法,在方法前后记录时间。 3. 在Controller定义一个需要计算耗时的方法,并在方法前加上@LogTime注解。 4. 使用AspectJ切面编程,在@Before获取目标方法并判断是否有@LogTime注解,如果有则使用CGLIB代理该方法并调用,实现计算方法耗时的功能。 示例代码如下: 1. 引入依赖 ``` <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.ow2.asm</groupId> <artifactId>asm</artifactId> <version>7.1</version> </dependency> ``` 2. 编写拦截器 ``` public class TimeInterceptor implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { long startTime = System.currentTimeMillis(); Object result = proxy.invokeSuper(obj, args); long endTime = System.currentTimeMillis(); System.out.println(method.getName() + " cost " + (endTime - startTime) + " ms"); return result; } } ``` 3. 定义需要计算耗时的方法 ``` @RestController public class TestController { @LogTime @GetMapping("/test") public String test() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "test"; } } ``` 4. 编写切面 ``` @Aspect @Component public class TimeAspect { @Autowired private ApplicationContext context; @Pointcut("@annotation(com.example.demo.annotation.LogTime)") public void logTime() { } @Before("logTime()") public void beforeLogTime(JoinPoint joinPoint) throws Throwable { Object target = joinPoint.getTarget(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); if (method.isAnnotationPresent(LogTime.class)) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(target.getClass()); enhancer.setCallback(new TimeInterceptor()); Object proxy = enhancer.create(); Method proxyMethod = proxy.getClass().getMethod(method.getName(), method.getParameterTypes()); proxyMethod.invoke(proxy, joinPoint.getArgs()); } } } ``` 5. 测试 启动Spring Boot应用,并访问http://localhost:8080/test,可以看到控制台输出以下信息: ``` test cost 1000 ms ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值