0

There are some similar questions, I checked them but could not find a solution to my problem. I am trying very basic spring application but getting error.

here is my appcontext.xml

<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.spring.springlegacy"></context:component-scan>

and my component

@Component("springService")
public class SpringServiceImpl implements SpringService{
    @Override
    public void giveService() {
        System.err.println("service given");
    }
}

and my wired variable

public class Printer {
    @Autowired
    private SpringService springService;

    public void print(){
        springService.giveService();
    }
}

and inside main method

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
Printer printer = new Printer();
printer.print();

and the error is

Exception in thread "main" java.lang.NullPointerException
    at com.spring.springlegacy.Printer.print(Printer.java:10)
    at com.spring.springlegacy.Main.main(Main.java:13)

What is missing here ?

PS: Since I am not using new keyword for spring managed objects, I believe this question is different from others.

cacert
  • 2,677
  • 10
  • 33
  • 56
  • I already saw this question but I dont use new keyword anywhere, how is it the duplicate question ? – cacert Mar 31 '16 at 20:31
  • `Printer printer = new Printer();` Define `Printer` as bean in `appcontext.xml` then do `getBean("printer")`. Or I gues you can make it `@Service` too. – Sanjay Rawat Mar 31 '16 at 21:46
  • Um, how is `new Printer()` "not using new"? – chrylis -cautiouslyoptimistic- Apr 01 '16 at 00:07
  • The dupe choice is right here. In the duplicate, the object they're newing up has their autowired instance returning `null`. In this case, it's no different -your newed up instance with an autowired field is also `null`. If you can demonstrate that the solutions in the duplicate are *not* applicable to your case, I will happily cast a reopen vote. – Makoto Apr 01 '16 at 01:32
  • In that qestion the "@service" annotated class is constructed with new. In my case I dont use Printer class as a spring managed bean. However as far as I understand from comments if I am autowiring a field of an object that holder object(in my case Printer) should also be managed by spring, so Printer object also should be "@service,@component" etc. is that true ? – cacert Apr 01 '16 at 07:09

0 Answers0