0

I am new to Spring and trying to understand the behavior of PostConstruct in Spring

Could anyone help me figure out why I get NPE on c, when its called from Caller class, when I am initialzing it in the init method.

public abstract class A extends B {
    
    private C c;
    
    @PostConstruct
    public void init() {
        
        c = new C();
    }


    @Override
    public D testMethod() {

     c.callMethod()     
    
    }
    
}

@Component
public class Caller {
    
    .....
    
    public void method() {
        // NPE on c 
        <code>.testMethod()
    }
    
}

ghostRider
  • 15
  • 3
  • 1
    add `@Autowired` above `private C c;`. Without that annotation the bean will not be injected into the field. Also, class A or a subclass that extends it should be annotated with `@Component` or the annotation is ignored. – Maurice Jul 10 '22 at 19:21
  • btw its better to implement the method `afterPropertiesSet()` from the `Spring` interface `InitializingBean` then to use `@PostConstruct`. `@PostConstruct` has been deprecated. – Maurice Jul 10 '22 at 19:26

0 Answers0