[英]Inject a class object in another class without adding it in the constructor
I have a Handler class in which I am using lombok to inject the dependencies and create the required args constructor.我有一个 Handler 类,我在其中使用 lombok 注入依赖项并创建所需的 args 构造函数。 The class looks like below:
该类如下所示:
@RequiredArgsConstructor(onConstructor = @__(@Inject))
class Handler {
private final @NonNull ObjectMapper objectMapper;
private final @NonNull UserAddressBookDao userAddressBookDao;
//Some methods below
}
Now I have to include/inject another class ie Controller class object in the handler class so the updated handler class would be:现在我必须在处理程序类中包含/注入另一个类,即控制器类对象,因此更新的处理程序类将是:
@RequiredArgsConstructor(onConstructor = @__(@Inject))
class Handler {
private final @NonNull Mapper mapper;
private final @NonNull UserDao userDao;
//newly added class member
private final @NonNull Controller controller;
//Some methods below ...'
}
I don't want the new class member in the constructor since I have used handler class at a lot of places in my service that If I add a new class member I would have to update code at all those places to add the new member into the constructor.我不希望在构造函数中使用新的类成员,因为我在我的服务中的很多地方都使用了处理程序类,如果我添加一个新的类成员,我将不得不在所有这些地方更新代码以将新成员添加到构造函数。 I want the new member to be excluded from the Handler class's constructor so that I can avoid this situation.
我希望从 Handler 类的构造函数中排除新成员,这样我就可以避免这种情况。 Also the controller class has a lot of members since initializing it will be a problem if I would try to at the required places.
此外,控制器类有很多成员,因为如果我尝试在所需的位置进行初始化,它将成为一个问题。 So, is there anyway I can inject Controller into my handler class without including that in the constructor.
那么,无论如何我可以将 Controller 注入到我的处理程序类中,而无需将其包含在构造函数中。 Thank you so much in advance and please forgive if the question sounds too vague.
非常感谢您,如果问题听起来太模糊,请原谅。 The controller class looks like this:
控制器类如下所示:
@Singleton
@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class Controller {
@NonNull
private final ABCService abcClient;
@NonNull
private final DdbDao DdbDao;
@NonNull
private final ServiceAccessor serviceAccessor;
`Some methods below ...`
@NotNull
annotation and final
modifier from Controller
field, as lombok will pick it up for @RequiredArgsConstructor
.Controller
字段中删除@NotNull
注释和final
修饰符,因为lombok会为@RequiredArgsConstructor
拾取它。final
should be removed anyway, as compiler requires it to be assigned by the constructor and you specifically don't want to set it in a constructor .final
,因为编译器要求它由构造函数分配,而您特别不想在构造函数中设置它。@NotNull
then look and lombok 's @SomeArgsConstructor
where you define explicitly which arguments will be set by the constructor.@NotNull
然后寻找和龙目岛的@SomeArgsConstructor
你定义明确哪些参数将通过构造函数中设置。@Inject
annotation to the setter for controller:@Inject
注解:@Inject public void setController(Controller controller) {this.controller = controller;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.