0

Following is the application any pointers where the error is

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
@SpringBootApplication
public class SpringAutoWApplication {

public static void main(String[] args) {
    SpringApplication.run(SpringAutoWApplication.class, args);
    DestClass dc = new DestClass();
    dc.showTestWired();
  }
}



import org.springframework.beans.factory.annotation.Autowired;
@Component
public class DestClass {

@Autowired
private TestWired testWired;

public void showTestWired() {
    System.out.println(testWired.getTestInt());
}

}

Class to be autowired

import org.springframework.stereotype.Component;


 @Component
public class TestWired {

 int testInt = 234;

public int getTestInt() {
    return testInt;
}

public void setTestInt(int testInt) {
    this.testInt = testInt;
}
}

Error:
Exception in thread "main" java.lang.NullPointerException at DestClass.showTestWired(DestClass.java:13)

the line where i am trying to call the print the int is returning a null pointer exception

Answer: After few hours of looking around this is the way it works, as I cannot post my answer I am doing it here

public class SpringAutoWApplication {
public static void main(String[] args) {
    ConfigurableApplicationContext context = SpringApplication.run(SpringAutoWApplication.class, args);
    DestClass dc = context.getBean(DestClass.class);
    dc.showTestWired();
 }

}

Joe G
  • 1
  • 2
  • Ok here goes the answer for this ` ConfigurableApplicationContext context = SpringApplication.run(SpringAutoWApplication.class, args); DestClass dc = context.getBean(DestClass.class);` With this you can create autowire. – Joe G May 17 '18 at 20:04

1 Answers1

1

Autowire only work on spring bean.

Your DestClass is not a bean. Hence no autowire occur, @Autowire has no effect.

Mark your DestClass with @Component will do it:

@Component
public class DestClass {

Moreover, you're initialize your own instance, not get from spring bean so your test bean is null:

   DestClass dc = new DestClass();

Instead, autowire DestClass in your SpringAutoWApplication class.

@Autowired
DestClass dc;

Finally it can be test like:

@SpringBootApplication
public class SpringAutoWApplication {

 @Bean
 String test(DestClass dc) {
    dc.showTestWired();
    return "work";
 }

  public static void main(String[] args) {
    SpringApplication.run(SpringAutoWApplication.class, args);
  }
}
Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51