设置“系统"控制器中的属性并在一个方面访问它 [英] set "systems" property in controller and access that in an aspect

查看:18
本文介绍了设置“系统"控制器中的属性并在一个方面访问它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使数据库国际化.我的任务是以尽可能少的更改来国际化数据库字段.我的问题是 - 如何从控制器方法将属性设置为线程并从我的方面访问该属性.System.setProperties() 显然不是线程安全的.

I am working on internationalizing the database. My task is internationalize database fields with least amount of changes possible. My question is- how can I set properties to a thread from controller method and access that property from my aspect. System.setProperties() is obviously not thread safe.

class Title {
    ...
    private String description;
    ...
}

@Entity
Class Language {
    ...
    private String name;
    ...

    public static String fingLanguageByName(String name) {
        ...
        return l;
    }
}

@Entity
Class InternationalizedTitle {
    ...
    private Title title;
    private String description;
    private Language language;
    ...
    public static String findDescriptionByTitleAndDate(Title t, Language l) {
        ...
        return d;
    }
    ...
}

@Controller
class TitleController {
    ...
    public TitleResponse getTitle(HttpServletRequest request, HttpServletResponse response) {
        if (request.isComingFromFrance()){


            ***System.setProperty("language", "French");***

        }
        return titleService.getTitleResponse(request);
    }
    ...
}

@Aspect
InternationalizationAspect {
    ...
    @Around("execution(* com.*.*.*.Title.getDescription(..))")
    public String getInternationalizedTitleDescription(ProceedingJoinPoint joinPoint) throws Throwable {
        ***String language = System.getProperty("language");***
        if (language == null) {
            return joinPoint.proceed();
        } else {
            Title t = (Title) joinPoint.getTarget();
            return InternationalizedTitle.findDescriptionByTitleAndDate(t,Language.findLanguageByName(name))
        }
    }
    ...
}

推荐答案

如果您正在使用单线程模型,则可以使用 ThreadLocal.要么使用带有 public static final ThreadLocal 字段的类,要么使用带有实例字段的单例 bean.

If you're working with the single thread model, you can use a ThreadLocal. Either use a class with a public static final ThreadLocal field or make a singleton bean with an instance field.

您在 ThreadLocal 中放入的内容完全取决于您.如果您只需要该语言的 String 值,您可以简单地输入一个 String 值.

What you put in the ThreadLocal is entirely up to you. If you only need a String value for the language, you could simply put a String value.

private ThreadLocal<String> language = new ThreadLocal<>();

每个线程将始终访问自己的对象.

Each thread will always be accessing its own object.

这篇关于设置“系统"控制器中的属性并在一个方面访问它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆