Weld @Produces 依赖项具有空注入点
Weld @Produces dependency has null injection point
我有一个带有非默认构造函数的通用 DAO,看起来像这样(实际上与车辆无关,我只是想提供一个简单的示例)
public class GenericVehicleDao<T extends Vehicle> {
private Class<T> clazz;
@Inject
private DaoHelper daoHelper;
public GenericDao(Class<T> clazz)
{
this.clazz = clazz;
}
}
我有另一个 class 和一些使用此构造函数的 @Produces 方法,例如
public class AppProducer {
@Produces
public GenericDao<Car> createCar() {
return new GenericDao(Car.class);
}
@Produces
public GenericDao<Truck> createTruck() {
return new GenericDao(Truck.class);
}
}
然后我可以将该 DAO 注入服务层,例如
@Stateless
public class VehicleService {
@Inject
private GenericVehicleDao<Car> carDao;
}
Car DAO 可以很好地注入服务层,但是我发现在构建 DAO 后注入的 DAO DaoHelper
为空。如果我将 DaoHelper 注入到服务层中,那么注入很好,但我宁愿在 DAO 本身中进行注入。我试过从现场注入切换到 setter 注入,但我遇到了同样的问题。
再次回答我自己的问题,这可能对其他人有用。经过更多谷歌搜索后,我在 Weld documentation
中发现了以下内容
There's one potential problem with the code above. The implementations
of CreditCardPaymentStrategy are instantiated using the Java new
operator. Objects instantiated directly by the application can't take
advantage of dependency injection and don't have interceptors.
If this isn't what we want, we can use dependency injection into the
producer method to obtain bean instances:
这意味着我可以更改我的 Producer 方法以采用以下格式,然后它就可以正常工作
@Produces
public GenericDao<Car> createCar(DaoHelper helper) {
GenericDao<Car> carDao = new GenericDao<>(Car.class);
carDao.setHelper(helper);
return carDao;
}
我有一个带有非默认构造函数的通用 DAO,看起来像这样(实际上与车辆无关,我只是想提供一个简单的示例)
public class GenericVehicleDao<T extends Vehicle> {
private Class<T> clazz;
@Inject
private DaoHelper daoHelper;
public GenericDao(Class<T> clazz)
{
this.clazz = clazz;
}
}
我有另一个 class 和一些使用此构造函数的 @Produces 方法,例如
public class AppProducer {
@Produces
public GenericDao<Car> createCar() {
return new GenericDao(Car.class);
}
@Produces
public GenericDao<Truck> createTruck() {
return new GenericDao(Truck.class);
}
}
然后我可以将该 DAO 注入服务层,例如
@Stateless
public class VehicleService {
@Inject
private GenericVehicleDao<Car> carDao;
}
Car DAO 可以很好地注入服务层,但是我发现在构建 DAO 后注入的 DAO DaoHelper
为空。如果我将 DaoHelper 注入到服务层中,那么注入很好,但我宁愿在 DAO 本身中进行注入。我试过从现场注入切换到 setter 注入,但我遇到了同样的问题。
再次回答我自己的问题,这可能对其他人有用。经过更多谷歌搜索后,我在 Weld documentation
中发现了以下内容There's one potential problem with the code above. The implementations of CreditCardPaymentStrategy are instantiated using the Java new operator. Objects instantiated directly by the application can't take advantage of dependency injection and don't have interceptors.
If this isn't what we want, we can use dependency injection into the producer method to obtain bean instances:
这意味着我可以更改我的 Producer 方法以采用以下格式,然后它就可以正常工作
@Produces
public GenericDao<Car> createCar(DaoHelper helper) {
GenericDao<Car> carDao = new GenericDao<>(Car.class);
carDao.setHelper(helper);
return carDao;
}