0

I had an issue to autowire an object in my abstract base class. It always give me null instead of an instance. Please help.

Base class:

public abstract class BaseClass implements IReq<Req> {

    @Autowired
    protected ReqDao dao;

    protected void updateReq() {
         dao.update();
    } 
}

Child class:

@Component
public class ChildClass extends BaseClass {
    ...
}

ReqDao class:

@Component
public class RptRequestDao {
     public void update(){
          ...
     }
}

I am thinking of simply use the update() function in Base class, which means in my ChildClass, I don't override that one. Is this the problem? If it is, what's the normal way to do it? Thanks in advance.

Laodao
  • 1,547
  • 3
  • 17
  • 39
  • Are you sure you have ReqDao in the context? How do you instanciate and use ChildClass? I reproduced your code above, it works as expected. – Andriy Slobodyanyk May 20 '17 at 13:31
  • @AndriySlobodyanyk, I use new ChildClass() to instantiate it. – Laodao May 20 '17 at 14:16
  • Possible duplicate of [Spring, abstract class and annotations](https://stackoverflow.com/questions/2921899/spring-abstract-class-and-annotations) – Aelphaeis Nov 06 '17 at 17:41

4 Answers4

0

A bean is created on demand, in your case when you initialize your object, RepoDao is private so it wont be inhereted to the class which will be intialized, you either need to put

@Component
public class ChildClass extends BaseClass {
    @Autowired
    private ReqDao dao;

or make it protected/public in BaseClass, sure public will make it accessible to other classes which violates the encapsulation

Amer Qarabsa
  • 6,412
  • 3
  • 20
  • 43
0

Instantiate your child class using @Autowired like this

public class SomeClass{

@Autowired
ChildClass childClass; //IMPORTANT

}

The error occurs when you try to instantiate the childClass like this:

public class SomeClass{

ChildClass childClass = new ChildClass();

}
nanospeck
  • 3,388
  • 3
  • 36
  • 45
-1

BaseClass is abstract you can't instantiate it.You need to have your ReqDao in ChildClass to be autowired.Spring will only autowire when it will create an instance of that class.Hope that helps

Nitin Prabhu
  • 624
  • 6
  • 10
-1

Check how you are instantiating the child class. Make sure you are NOT using "new" keyword to instantiate child class.

ChildClass cc = new ChildClass() // **Not recommended**

You must autowire the childclass and let spring take care of bean creation.

Chandan Kumar
  • 1,066
  • 10
  • 16