-2

Test.java

@Service
public class Test {

public void Testing() {
    System.out.println("inside testing");
}
}

here is my factory class

@Service
 public class ClaimFactory extends BaseClaimFactory {

   @Autowired
   ClaimProvider claimProvider;

@Override
public ClaimProvider getClaimRequest( String type) throws Exception {

    if (type.equals(ClaimProviderEnums.ABC.toString())) {

         claimProvider = new ABCIMP();
    }

    return claimProvider;
}

}

Here is my ABCIMP.java class

@Service
public class ABCIMP implements ClaimProvider {

@Autowired
Test test;

public void claimRequest(){
      test.testing();
   }

}

i calling like this

     claimProviders=baseClaimFactory.getClaimRequest();
     claimProviders.claimRequest();

i dono why i get java.lang.NullPointerException on line test.testing() does anybody know why this is happing and it is working when i call aBCIMP.claimRequest()

  • Isnt `ABCIMP` a `Component`, not a `Service`. I would ask the same question for your `Test` class as well. – Dan Aug 23 '18 at 15:09
  • coz its a Service layer ABCIMP.java. ..even with component is not working – Gaurav Singh Aug 23 '18 at 15:13
  • Yes, it won't work when you dont let the IOC container take care of proxying the objects for you. You cannot do `new X()` and expect Spring to manage that for you. – Dan Aug 23 '18 at 15:15
  • When i return `Autowire ABCIMP aBCIMP;` and return it like `return aBCIMP ` in getClaimRequest and then i get null pointer at ` claimProviders.claimRequest();` – Gaurav Singh Aug 24 '18 at 02:35

1 Answers1

0

You have created ABCIMP instance with new ABCIMP();. Spring Framework won't process objects created with Java new operator unless you have configured AspectJ Proxies.

Do not create new instance, use only @Autowired to obtain existing instance from Spring context. Remove the ClaimFactory class completely, you are repeating Spring's work. If you need to get the instance in the runtime:

@Autowired
private ApplicationContext ctx;

...

if (type.equals(ClaimProviderEnums.ABC.toString())) {
     return ctx.getBean(ABCIMP.class);
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111