gpt4 book ai didi

java - Jersey 多个构造函数@inject

转载 作者:行者123 更新时间:2023-12-02 12:43:57 24 4
gpt4 key购买 nike

我正在为我的 Jersey 资源创建两个构造函数,但是只有一个可以调用,

这是示例代码,

public class jerseyresoure {
private String name;
private int age;

@Inject
public jerseyresoure (String name){
this.name = name;
}

@Inject
public jerseyresoure (int age){
this.age= age;
}
}

参数为int的get构造函数是调用成功的构造函数,你能帮我解决这个问题吗?

最佳答案

根据 CDI 规范,使用 @Inject 注解多个构造函数是非法的(请参阅 CDI 规范第 3.9 节):

If a bean class does not explicitly declare a constructor using @Inject, the constructor that accepts no parameters is the bean constructor.

If a bean class has more than one constructor annotated @Inject, the container automatically detects the problem and treats it as a definition error.

A bean constructor may have any number of parameters. All parameters of a bean constructor are injection points.

所以你可以做如下:

public class jerseyresoure {
private String name;
private int age;

@Inject
public jerseyresoure (String name, int age){
this.name = name;
this.age = age;
}

}

我假设您正在使用生产者方法,以便注入(inject)值(nameage)。

关于java - Jersey 多个构造函数@inject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44849507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com