1

I need to create a new EmployeeInfoCache instance (not a singleton) from info in the HttpServletRequest that is used to get info from an external app. I then want to give this object as a dependency to non-web-layer objects (where it will be set for all @Autowired references). EmployeeInfoCache itself has no web-layer dependencies (e.g. HttpServletRequest).

Can this be done? I thought about writing a spring interceptor which does the following but I don't know what to do to put an object in the spring context such that it will be used to resolve all @Autowired dependencies.

e.g.

public class MyInterceptor extends HandlerInterceptorAdapter 
{
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception 
    {
        - use info from HttpServletRequest to make calls to external app
        - create EmployeeInfoCache object w/ this info
        - add EmployeeInfoCache to spring application context where it will be used for resolution of @Autowired
    }
}

And the remaining code:

// Assume don't have 'Component' or a similar annotation?
public class EmployeeInfoCache
{
    ... 
}

// REST controller that calls the business logic method
@Controller
MyController
{
    @Autowired
    private MyBusinessObjectInterface myBusinessObject;

    @RequestMapping(...)
    public @ResponseBody MyResult myMethod(@RequestBody MyObject myObject, HttpServletRequest request, HttpServletResponse response)
    {
        myBusinessObject.doIt();
    }
}

//  Non-web-layer code that uses EmployeeInfoCache
@Service(...)
MyBusinessObject implements MyBusinessObjectInterface
{
    // I want the EmployeeInfoCache instance created in MyInterceptor to be autowired here
    @Autowired
    private EmployeeInfoCache employeeInfoCache;

    @Override
    public void doIt()
    {
        employeeInfoCache.getName();
    }
}
Meta
  • 77
  • 3
  • 12
  • It might be possible using a request scoped bean - it definitely wont be using the application context as this is created when spring starts. Have a look here: http://stackoverflow.com/questions/3320674/spring-how-do-i-inject-an-httpservletrequest-into-a-request-scoped-bean – stringy05 Feb 20 '15 at 00:30

1 Answers1

0

It sounds like you want to use a factory pattern. Have a Spring bean which is the factory method that returns the Cache.

http://kh-yiu.blogspot.in/2013/04/spring-implementing-factory-pattern.html

EdH
  • 4,918
  • 4
  • 24
  • 34