最近起了一个新的java服务,springboot项目,然后公司内部前端接口调用都通过gateway,同事写了一个公共的jar包,功能是从header中取用户信息,用户信息是gateway写进去的,然后我的新服务引了这个包,但是这玩意儿不起效,get完了是null,所以我去看了看代码,代码如下:
我的调用代码:
Map<String, Object> data = UserContextHolder.getInstance().getContext();
理论上,这个data里有登录用的id姓名之类的,但是get完了这个data是个null,好,继续往里找:
UsercontextHolder里有啥?
public class UserContextHolder {
private ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal();
private UserContextHolder() {
}
public static UserContextHolder getInstance() {
return UserContextHolder.SingletonHolder.sInstance;
}
public void setContext(Map<String, Object> map) {
this.threadLocal.set(map);
}
public Map<String, Object> getContext() {
return (Map)this.threadLocal.get();
}
public void clear() {
this.threadLocal.remove();
}
private static class SingletonHolder {
private static final UserContextHolder sInstance = new UserContextHolder();
private SingletonHolder() {
}
}
}
非常好,也很简单,那这玩意儿啥时候赋的值呢?应该在同一个包里,然后我找到了:
package com.aaa.bbb;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {
public TokenAuthenticationFilter() {
}
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String userInfo = httpServletRequest.getHeader("x-client-token-user");
// 这里省略了一部分,反正就是鼓捣了个map出来
HashMap user=parse(userInfo);
UserContextHolder.getInstance().setContext(user);
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
看不出有啥问题,启动服务发现这玩意儿没注册上,好的,copy一份到自己的代码里,可以运行,也能注册上。
那么,问题在哪儿呢???
又思考了一会儿,发现了问题所在,就是这个package,我的启动类所在package为:
package com.aaa.ccc;
这个filter的package为:
package com.aaa.bbb;
所以,在启动类上加上:
@ComponentScan(basePackages = {"com.aaa"})
就可以了。