ServiceInvokerImpl.javaObject lService = null;
lService = Class.forName("com.test.AssetServiceImpl").newInstance();
AssetServiceImpl.javapublic 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);
}
When I instantiate AssetServiceImpl in ServiceInvokerImpl.java, it shows Autowired property entityLifeCycleManager of AssetServiceImpl.java as null. So, how autowire will work for manual instantiation for above scenario ?
@Autowired only works for managed instances, i.e. object instances which are created by a Dependency Injection container (for @Autowired, this is Spring).
So if you just invoke Class#getInstance() (which is basically the same as instantiate with new operator), @Autowired is just ignored, and entityLifeCycleManager will be null.
If you still need to instantiate it manually (and not with Spring), you could use constructor injection and manually supply the dependency, for example:
public class AssetServiceImpl implements LogisticService {
private final EntityLifeCycleManager entityLifeCycleManager;
@Autowired
public AssetServiceImpl(EntityLifeCycleManager entityLifeCycleManager) {
this.entityLifeCycleManager = entityLifeCycleManager;
}
...
and then instantiate it either with new operator:
EntityLifeCycleManager entityLifeCycleManager = //.. somehow obtain an EntityLifeCycleManager instance
LogisticService logisticService = new AssetServiceImpl(entityLifeCycleManager);
or via Class:
EntityLifeCycleManager entityLifeCycleManager = //.. somehow obtain an EntityLifeCycleManager instance
LogisticService logisticService = Class.forName("com.test.AssetServiceImpl").getConstructor(new Class[]{EntityLifeCycleManager.class}).newInstance(new Object[]{entityLifeCycleManager});
Please note that @Autowired annotation is moved to the constructor to still allow this service be created and autowired by Spring if you like so.
Also it is worth noting that field injection (which is used in our initial example) is not recommended. The reason is that same usecase: it is difficult to instantiate (and properly inject with collaborators) a class that uses field injection. Constructor injection is better in this regard.