0

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.

njdeveloper
  • 1,465
  • 3
  • 13
  • 16

2 Answers2

2

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.

sourcedelica
  • 23,940
  • 7
  • 66
  • 74
1

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().

sourcedelica
  • 23,940
  • 7
  • 66
  • 74
  • Can we autowire a class into a bean which is not created by Spring. For example, MyItem can be created from multiple classes, and I can't always pass in this requestBean when I create the MyItem class. – njdeveloper May 10 '11 at 08:03
  • Yes, see this answer: http://stackoverflow.com/questions/3813588/how-to-inject-dependencies-into-a-self-instantiated-object-in-spring. – sourcedelica May 10 '11 at 15:51
  • 1
    I posted another solution which is preferable. – sourcedelica May 10 '11 at 16:18
  • Unfortunately, both solutions regarding autowiring a bean not created by Spring did not work. Any other ideas? – njdeveloper May 11 '11 at 14:35