Answer the question
In order to leave comments, you need to log in
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()
);
}
}
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();
}
}
package lessons.started;
import org.springframework.stereotype.Component;
@Component
public class GreetingServiceImpl {
public String sayGreeting() {
return "Greeting, user!";
}
}
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)
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question