ServiceInvokerImpl.java
Object lService = null;
lService = Class.forName("com.test.AssetServiceImpl").newInstance();
AssetServiceImpl.java
public class AssetServiceImpl implements LogisticService {
@Autowired
private EntityLifeCycleManager entityLifeCycleManager;
@Override
@Transactional
public FetchResults findAsset(String cls, QueryDetail query, OperationProperties props) {
return entityLifeCycleManager.find("com.test.model.Asset", query, props);
}
问题描述
当我在 ServiceInvokerImpl.java
中实例化 AssetServiceImpl
时,它显示 AssetServiceImpl 的
为空。那么, Autowiring 将如何用于上述场景的手动实例化?Autowired
属性 entityLifeCycleManager
.java
最佳答案
@Autowired
仅适用于托管实例,即由依赖注入(inject)容器创建的对象实例(对于 @Autowired
,这是 Spring)。
因此,如果您只是调用 Class#getInstance()
(这与使用 new
运算符实例化基本相同),@Autowired
就是只是被忽略,entityLifeCycleManager
将为 null
。
如果您仍然需要手动实例化它(而不是使用 Spring),您可以使用构造函数注入(inject)并手动提供依赖项,例如:
public class AssetServiceImpl implements LogisticService {
private final EntityLifeCycleManager entityLifeCycleManager;
@Autowired
public AssetServiceImpl(EntityLifeCycleManager entityLifeCycleManager) {
this.entityLifeCycleManager = entityLifeCycleManager;
}
...
然后使用 new
运算符实例化它:
EntityLifeCycleManager entityLifeCycleManager = //.. somehow obtain an EntityLifeCycleManager instance
LogisticService logisticService = new AssetServiceImpl(entityLifeCycleManager);
或通过类
:
EntityLifeCycleManager entityLifeCycleManager = //.. somehow obtain an EntityLifeCycleManager instance
LogisticService logisticService = Class.forName("com.test.AssetServiceImpl").getConstructor(new Class[]{EntityLifeCycleManager.class}).newInstance(new Object[]{entityLifeCycleManager});
请注意,@Autowired
注释已移至构造函数,以便仍然允许 Spring 创建并 Autowiring 此服务(如果您愿意的话)。
此外值得注意的是,不建议使用字段注入(inject)(在我们最初的示例中使用)。原因是相同的用例:很难实例化(并与协作者正确注入(inject))使用字段注入(inject)的类。构造函数注入(inject)在这方面更好。
关于java - Autowiring 在手动对象实例化中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42890093/