简体   繁体   English

根据请求参数自动装配请求范围的bean

[英]Autowiring a request-scoped bean based on a request parameter

In a spring controller, I can do the following: 在弹簧控制器中,我可以执行以下操作:

@Controller
public class FooController {

    @Autowired 
    private FooServiceFactory factory;

    @RequestMapping("foo")
    public Foo createFoo(@RequestParam String kind, @RequestParam String id) {
        FooService service = factory.getFooService(kind);
        return service.get(id);
    }
}

Now, if I had lots of methods that took a kind and started with FooService service = factory.getFooService(kind); 现在,如果我有很多采用kind方法并以FooService service = factory.getFooService(kind);开始的方法FooService service = factory.getFooService(kind); , then it would be nice to be able to move all that logic out to the controller. ,那么将所有逻辑移到控制器上将是一个不错的选择。

Is there any other place in the controller with access to the request parameters? 控制器中是否还有其他地方可以访问请求参数?

Is there some way of effectively saying (I'm making up the syntax here): 有没有一种有效的说法(我在这里构成语法):

private FooService service;

@Autowired 
public setKind(@RequestParam String kind) {
    service = factory.getFooService(kind);
}

Or is there some better way of encapsulating common parameters such as this? 还是有一些更好的方法来封装诸如此类的通用参数?

If you use an instance variable to store FooService you must make sure you implement FooService with thread safety in mind. 如果使用实例变量存储FooService ,则必须确保在实现FooService时牢记线程安全。 So best thing is instead of using the following style of coding. 因此,最好的方法是不要使用以下编码样式。

private FooService service;

@Autowired 
public setKind(@RequestParam String kind) {
    service = factory.getFooService(kind);
}

What you can do is; 你能做的是

private FooService _getFooService(String kind) {
    return factory.getFooService(kind);
}

and use this inside all your controllers; 并在所有控制器中使用它;

@RequestMapping("foo")
public Foo createFoo(@RequestParam String kind, @RequestParam String id) {
    return _getFooService(kind).get(id);
}

That way you can eliminate code duplication while guaranteeing thread safety. 这样,您就可以在确保线程安全的同时消除代码重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM