24.12.31 SpringBootDay02

发布于:2025-02-11 ⋅ 阅读:(61) ⋅ 点赞:(0)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SaveLog {
}
@Component
@Aspect
public class LogAspect {

    @Resource
    HttpSession session;
    @Resource
    SystemLogService logService;

    @Around("@annotation(com.javasm.bootdemo.common.interfaces.SaveLog)")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        //获取用户信息
        Object user = session.getAttribute("user");
        Integer uid = -1;
        if (user != null){
            WebUser webUser = (WebUser) user;
            uid = webUser.getUid();
        }
        //获取类名
        String className = joinPoint.getTarget().getClass().getName();
        //方法名
        String methodName = joinPoint.getSignature().getName();
        //参数
        Object[] args = joinPoint.getArgs();
        String argsString = Arrays.toString(args);
        //组装参数
        SystemLog systemLog = new SystemLog(uid,className,methodName,argsString);
        logService.insert(systemLog);
        return proceed;
    }
}

事务

开启事务

@EnableTransactionManagement//开启事务
需要开启事务的方法上
@Transactional
事务是否生效,完全看是否抛出异常
    看方法是否向spring抛出异常
  • 在调用的一方,添加@Transactional
    • 事务生效了
  • 在被调用的一方,
    • 事务没有生效
  • 使用try...catch捕获异常,并打印,导致事务失效

Spring的事务机制,是看调用的方法,是否抛出异常

不要在每一个方法上都加@Transactional

只有多表调用的时候,才建议使用事务

跨域

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter(){
        //预先的配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //所有的请求,都要过滤,都添加跨域
        source.registerCorsConfiguration("/**",buildConfig());
        return new CorsFilter(source);
    }
    private CorsConfiguration buildConfig(){
        CorsConfiguration config = new CorsConfiguration();
        //配置 允许所有的作用域
        config.addAllowedOrigin("*");
        //头信息
        config.addAllowedHeader("*");
        //方法
        config.addAllowedMethod("*");
        //cookie,session会失效
        config.setAllowCredentials(true);
        //有效期
        config.setMaxAge(3600L);

        return config;
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到