I just can't figure out how the @Autowired abstract works in Spring. So, let's say I have Interface1 like this:
public interface Interface1 { String getString(); } He has only one method. The following class, being @Service, implements this simple interface:
@Service public class Interface1Impl implements Interface1 { public String getString() { return "Hello!"; } } Now I want to use an instance of this class somewhere along with the @Autowired annotation. I create the following class Instance1:
@Service public class Instance1 { @Autowired Interface1 field; public void doSomething() { System.out.println(field.getString()); } } Next, in the main method of my main class, I do the following:
public class MainClass { public static void main(String[] args) { Instance1 instance = new Instance1(); instance.doSomething(); } } However, a NullPointerException appears due to the fact that the field with the annotation @Autowired was left without an assigned value. I don’t understand why this is so, and generally I don’t understand how Spring works in this situation. Please explain to me how to fix the code so that in the main method I can call instance methods.