-2

I have a HelloService(@Service) class. I am trying to Autowire an ApplicationContext member in my class.
But it is not working . My context object is null.

Here is the HelloService Class

@Service
public class HelloService {
    @Autowired
    private ApplicationContext context;
    public String getHello(){
        if(context == null){
            return "Autowiring didn't work. No Hello from the service";
        }
        else{
            return "Hello";
        }
    }
}

My HelloService class is marked as @Service. Hence now spring knows that it is a bean, and it should do the AutoWiring of ApplicationContext bean, which is managed by spring.


Here is how I am verifying that context object is null. I have made a simple Controller HelloController, mapping to \hello .

@RestController
public class HelloController {
    @Autowired
    private ApplicationContext context;

    @GetMapping("/hello")
    public String getHello(){
        if(context!=null)
            System.out.println("ApplicationContext object is Autowired in RestController.");

        return (new HelloService()).getHello();
    }
}

Whenever make a request to http://localhost:8080/hello ,
I get this response : Autowiring didn't work. No Hello is there ,
and this output on command line

ApplicationContext object is Autowired in RestController.

My Question :

  • Why ApplicationContext object is Autowired in an @RestController, but it is not being Autowired in an @Service ?

I have tried Why is my Spring @Autowired field null? : In this question OP didn't used @Service in the class he was doing the Autowiring, but I am using @Service.

I have tried a lot of other questions, that didn't helped either :
Cannot Autowire Service in HandlerInterceptorAdapter
https://stackoverflow.com/questions/8091203/spring-dependency-injection-autowiring-null

1 Answers1

2

You are creating your service bean using new keyword hence it is not working. Instead of creating that object using new keyword, use autowiring or inject. i.e

@RestController
public class HelloController {
    @Autowired
    private ApplicationContext context;

    @Autowired
    private HelloService service;

    @GetMapping("/hello")
    public String getHello(){
        if(context!=null)
            System.out.println("ApplicationContext object is Autowired in RestController.");

        return service.getHello();
    }
}

For more information read about autowired vs new

Pirate
  • 2,672
  • 4
  • 21
  • 39