A
A
afna2016-07-07 18:27:44
Java
afna, 2016-07-07 18:27:44

What's wrong with dependency injection?

Hello!
I'm learning DI.
Created three simple classes:

1.

package lessons.started;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Starter {
    private static final Logger logger = LogManager.getLogger(Starter.class);

    @Autowired
    private static GreetingServiceImpl greetingService;

    public static void main(String[] args) {
        logger.info("Starting configuration...");
        ApplicationContext context = new AnnotationConfigApplicationContext(LessonsConfiguration.class);
        logger.info(
                greetingService.sayGreeting()
        );
    }
}


2.
package lessons.started;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class LessonsConfiguration {

    @Bean
    public GreetingServiceImpl greetingService(){
        return new GreetingServiceImpl();
    }
}


3.
package lessons.started;

import org.springframework.stereotype.Component;

@Component
public class GreetingServiceImpl {

    public String sayGreeting() {
        return "Greeting, user!";
    }
}


When starting the application, in addition to other logs, an error flies:
Exception in thread "main" java.lang.NullPointerException
  at lessons.started.Starter.main(Starter.java:22)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:497)
  at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)


those. greetingService reference was not assigned a value.

Why doesn't Dependency Injection work?
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
#
#algooptimize #bottize, 2016-07-07
@sulik93

and here
new AnnotationConfigApplicationContext(LessonsConfiguration.class)
and
starter
@Autowired
private static GreetingServiceImpl greetingService;
?
So there is nothing like in the code to initialize that field.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question