[英]Call Spring service and send params via Constructor
I have this simple Spring Service:我有这个简单的 Spring 服务:
@Service
public class BinCountryCheckFilterImpl {
@Autowired
private RiskFilterService riskFilterService;
private Terminals terminal;
@Autowired
public BinCountryCheckFilterImpl(Terminals terminal) {
this.terminal = terminal;
}
}
Terminals
is a object unique for each received request. Terminals
是一个 object 对于每个收到的请求都是唯一的。 Also binCountryCheckFilter
should be unique for every request - it should check the data for some business condition.此外
binCountryCheckFilter
对于每个请求都应该是唯一的 - 它应该检查数据的某些业务状况。
I want to call the service from here:我想从这里调用服务:
@Service
public class FilterProcessing {
@Autowired
private BinCountryCheckFilterImpl binCountryCheckFilter;
public Response someMetohd(Terminals terminal,
Transaction message, HttpServletRequest request) throws JAXBException, JsonProcessingException {
switch(.......) {
case ".......":
// send here the args via Contructor
binCountryCheckFilter.validateBinCountryCheckFilter(terminal);
break;
case ".........":
.........
break;
break;
}
}
return null;
}
}
But I'm not aware how to send the object terminal
via the BinCountryCheckFilterImpl
constructor.但我不知道如何通过
BinCountryCheckFilterImpl
构造函数发送 object terminal
。 Is there some solution for this?有什么解决办法吗?
Constructor is meant to create objects.构造函数是用来创建对象的。 You say: "send here the args via Constructor" - but this means that you should create a new object of type
BinCountryCheckerFilterImpl
for every request, and this is not how that class is defined.您说:“通过构造函数向此处发送参数”-但这意味着您应该为每个请求创建一个
BinCountryCheckerFilterImpl
类型的新 object,这不是 class 的定义方式。
In your case BinCountryCheckFilterImpl
is a bean with (default) scope singleton, meaning that only one instance of this class exists in the application context.在您的情况下,
BinCountryCheckFilterImpl
是一个具有(默认)scope singleton 的 bean,这意味着应用程序上下文中仅存在此 class 的一个实例。
So instead of using parameter in constructor, just pass Terminals
object (that is created per request) into the validation method:因此,不要在构造函数中使用参数,只需将
Terminals
object(根据请求创建)传递到验证方法中:
@Service
public class BinCountryCheckFilterImpl {
@Autowired
private RiskFilterService riskFilterService;
public void validateBinCountryCheckFilter(Terminals terminal) {
}
}
If you really have to define the BinCountryCheckFilterImpl
to be a prototype, you should be aware that prototypes cannot be injected into singletons by simple Autowiring.如果你真的必须将
BinCountryCheckFilterImpl
定义为原型,你应该知道原型不能通过简单的自动装配注入到单例中。
There are many techniques for this, you can find the answers here .这有很多技巧,你可以在这里找到答案。 I don't describe them in the answer because I feel its out of scope of the question and you should really go with the solution I've provided above.
我没有在答案中描述它们,因为我觉得它超出了问题的 scope 并且你真的应该使用我上面提供的解决方案 go 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.