将动态创建的Spring bean实例添加到应用程序上下文以获取自动连接的依赖项

时间:2015-02-20 00:15:32

标签: java spring

我需要从HttpServletRequest中的info创建一个新的EmployeeInfoCache实例(不是单例),用于从外部应用程序获取信息。然后,我想将此对象作为非Web层对象的依赖项(将为所有@Autowired引用设置它)。 EmployeeInfoCache本身没有Web层依赖(例如HttpServletRequest)。

可以这样做吗?我想过编写一个执行以下操作的spring拦截器,但我不知道如何将一个对象放在spring上下文中,以便它可以用来解析所有@Autowired依赖项。

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
    }
}

剩下的代码:

// 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();
    }
}

1 个答案:

答案 0 :(得分:0)

听起来你想要使用工厂模式。有一个Spring bean,它是返回Cache的工厂方法。

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