Spring问题记录

1.线程安全问题
SpringBean默认情况下都为单例,如controller,service,但Controller在实际使用中一定是并发访问的,这就涉及线程安全问题。

是否会出现线程安全问题要分两种情况:
一:controller中没有成员变量,或者有成员变量但是是无状态的。

如果没有成员变量,虽然是多线程去操作controller这个单例,但是都只是调用其方法,而方法在调用时开辟的内存空间在虚拟机栈,栈空间是线程私有的,不会出现线程安全问题。

如果有成员变量,但是是无状态的,比如注入controller的service。(无状态既是类中只有方法,虽然service中可能有被注入的mapper,但mapper中是只有方法的,所以最终没有可改写的具体值,还是无状态。)那么等同于没有成员变量。

二:controller或service中有成员变量
一般情况下,不要给这些类中增加成员变量,可以通过方法传参的方式传入操作数。但如果必须有成员变量,就要考虑解决线程安全问题。
1:在controller类中,使用@Scope(“prototype”)注解,变为多例,。

@RestController
@Scope("prototype")
public class UserController {
...}

2:使用Threadlocal构建成员变量。

ThreadLocal<Integer> t=new ThreadLocal<>();
//在方法中使用时再从ThreadLocal获取
void method(){
Integer i=t.get();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,我们可以使用AOP(面向切面编程)来记录方法调用的时间。 首先,我们需要在pom.xml文件中添加Spring AOP的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 接下来,我们定义一个切面类,该类用于定义在方法调用前后要执行的逻辑。可以使用@Aspect注解来声明切面类,同时使用其他注解来指定切点和通知类型。例如,我们可以使用@Around注解来定义一个环绕通知,该通知会在方法调用前后执行: ```java @Aspect @Component public class MethodExecutionTimeAspect { private static final Logger LOGGER = LoggerFactory.getLogger(MethodExecutionTimeAspect.class); @Around("execution(* com.example.service.*.*(..))") public Object logMethodExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object result = joinPoint.proceed(); long endTime = System.currentTimeMillis(); long executionTime = endTime - startTime; LOGGER.info("Method {} execution time: {} ms", joinPoint.getSignature().toShortString(), executionTime); return result; } } ``` 在上面的例子中,我们定义了一个logMethodExecutionTime方法,并将其标记为@Around注解。@Around注解的参数表示了切点表达式,这里的execution(* com.example.service.*.*(..))表示所有位于com.example.service包下的方法都会被拦截。 在logMethodExecutionTime方法中,我们使用System.currentTimeMillis()来获取方法调用的开始时间和结束时间,并计算出方法执行的时间差。然后,我们使用Logger来记录方法的执行时间。 最后,在Spring Boot的主类上添加@EnableAspectJAutoProxy注解来启用AOP功能: ```java @SpringBootApplication @EnableAspectJAutoProxy public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 通过以上步骤,我们就可以在Spring Boot中记录方法调用的时间了。每当调用标记了@Around注解的方法时,AOP切面会自动将执行时间记录到日志中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值