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.

  • But it will not be initialized with you, because you don’t launch the application itself, but simply pull the interface - GenCloud
  • I see that it is not initialized, well, I ask, how can I use Spring and annotations to be able to access the methods of my class from main?) - Vladimir Dorovsky

1 answer 1

The "magic" of Spring annotations only works within the Spring context. Which you need to create. Here is some approximation of what you are trying to do in main :

 @Configuration @ComponentScan(basePackages = "your.package") public class MainClass { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(MainClass.class); Instance1 inst = ctx.getBean(Instance1.class); inst.doSomething(); } } 

But in Spring-based applications, it is not customary to do any logic in main , except for some basic initialization of Spring itself, since this code is outside the context of the application.

  • Thank you very much for such a detailed explanation! - Vladimir Dorovsky