我可以这样配置Spring吗,我将一个属性"isHttps"添加到请求中,并且可以从代码中的任何位置访问此属性,例如bean类:
public class MyItem{
public String getImageUrl(){
if (isHttps){
//return https url
}
//return http url;
}
}
我可以使用 ThreadLocal 来做到这一点,但我想避免走这条路。
另一种选择:
您可以按如下方式获取当前请求:
ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest req = sra.getRequest();
这在幕后使用线程本地。
如果你使用的是Spring MVC,这就是你所需要的。 如果您没有使用Spring MVC,则需要在web.xml
中注册RequestContextListener或RequestContextFilter。
创建一个请求范围的 Bean
<bean id="requestBean" class="com.foo.RequestBean" scope="request"/>
然后在该类中,自动连接请求(此处参考):
@Autowired
private HttpServletRequest request;
在 RequestBean 中添加一个方法,用于确定请求是否为 HTTPS。
public boolean isHttp() { // ... }
然后将 requestBean 注入到其他需要调用 isHttp() 的 bean 中。