0

Spring の動的データソース ルーティングチュートリアルに関するチュートリアルに従いました。そのためには、AbstractRoutingDataSource を拡張して、Spring に取得するデータソースを伝える必要があるため、次のようにします。

public class CustomRouter extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return CustomerContextHolder.getCustomerType();
    }
}

customerType の値を保持する責任を負うクラスが見つかるまで、すべてがうまくいきます (セッション全体で同じである必要があります)。

    public class CustomerContextHolder {

        private static final ThreadLocal<Integer> contextHolder = new ThreadLocal<Integer>(); 

        public static void setCustomerType(Integer customerType) {
            contextHolder.set(customerType);
        } 
        public static Integer getCustomerType() {
            return (Integer) contextHolder.get();
        }
        public static void clearCustomerType() {
            contextHolder.remove();
        }
    }

これにより、スレッドにバインドされた変数 customerType が作成されますが、Spring と JSF を使用した Web アプリケーションがあり、スレッドではなくセッションであると考えています。そのため、スレッドA (ビュー)を使用してログイン ページに設定しましたが、スレッドB (休止状態) は、使用するデータソースを知るために値を要求しますnull。実際、このスレッドには新しい値があるためです。

スレッド境界ではなくセッション境界で行う方法はありますか?

私がこれまでに試したこと:

  • ビューに CustomRouter を挿入して、セッションに設定します: 機能しません。依存関係でサイクルが発生します
  • ThreadLocalを整数に置き換えます。機能しません。値は常に、最後にログインしたユーザーによって設定されます
4

1 に答える 1

1

FacesContext.getCurrentInstance()動作していますか?もしそうなら、あなたはこれを試すことができます:

public class CustomerContextHolder { 

    private static HttpSession getCurrentSession(){
             HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance()
                 .getExternalContext().getRequest();

             return request.getSession();
    }

    public static void setCustomerType(Integer customerType) {

       CustomerContextHolder.getCurrentSession().setAttribute("userType", customerType);

    }

    public static Integer getCustomerType() {

        return (Integer) CustomerContextHolder.getCurrentSession().getAttribute("userType");
    }

    public static void clearCustomerType() {
        contextHolder.remove(); // You may want to remove the attribute in session, dunno
    }
}
于 2012-10-02T15:47:10.847 に答える