开发者

Can we configure Spring to configure a property based on the scope of the request?

开发者 https://www.devze.com 2023-03-03 19:30 出处:网络
Can I configure Spring in 开发者_如何转开发such a way that I add a property, \"isHttps\" to the request, and this property can be accessed from anywhere in the code, e.g. a bean class:

Can I configure Spring in 开发者_如何转开发such a way that I add a property, "isHttps" to the request, and this property can be accessed from anywhere in the code, e.g. a bean class:

    public class MyItem{
       public String getImageUrl(){
          if (isHttps){
            //return https url 
          }
      //return http url;
       }
    }

I can do this using ThreadLocal, but I would like to avoid taking that route.


Another alternative:

You can get the current request as follows:

    ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    HttpServletRequest req = sra.getRequest();     

This uses thread-local under the covers.

If you are using Spring MVC that's all you need. If you are not using Spring MVC then you will need to register a RequestContextListener or RequestContextFilter in your web.xml.


Create a request-scoped bean

<bean id="requestBean" class="com.foo.RequestBean" scope="request"/>

Then in that class, autowire the request (reference here):

@Autowired
private HttpServletRequest request;

Add a method in RequestBean that determines if the request is HTTPS.

public boolean isHttp() { // ... }

Then inject requestBean into your other beans that need to call isHttp().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号