简体   繁体   中英

getting nullPointerException while accessing an object after Autowiring using @Autowired

I have an Inteface C, wants to access getClassName() in two other class. Exception is coming in method1() while accessing a.getClassName().

public interface C {
void getClassName();
}
@Component
public class A implements C{
    @Override
    public void getClassName() {
        System.out.println(" IN A");
        }
}
@Component 
public class B implements C{
    @Override
    public void getClassName() {
        System.out.println(" IN B");
    }
}

Main Class

@Configurable
public class D {
    @Autowired
     A a;
    @Autowired
     B b;
    void method1() {
        a.getClassName();
    }
    void method2() {
        b.getClassName();
    }
    public static void main( String args[]) {
        D d =new D();
        d.method1();
        d.method2();
    }
} 

I read some blogs and tried Auto wiring D as well, but still same exception.

Placing annotations of Spring doesn't really mean you're using spring in the project.

There should be some kind of bootstrap code that creates an application context for you and establishes rules of where the beans (classes annotated with @Component in this case) should be found (scanning policy).

In addition, @Configurable is probably not the annotation you're looking for (its indeed exist and usually used with AspectJ related stuff, but not for this usecase).

You're probably trying to use spring boot here, so try the following approach:

  1. Go to: start.spring.io
  2. Configure an artifact of your choice (go with Jar as opposed to WAR)
  3. Download and open up the pom.xml in the IDE
  4. Add you beans in the package beneath the package where you'll find a file generated with @SpringBootApplication annotation and having the main method
  5. Run the project

This looks like spring-boot code. main() should have a SpringApplication.run() method. D is not being provided with instances of A and B in this code, therefore the error. You can use following code after removing main class from class D -

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);

        SpringApplicationBuilder builder = new SpringApplicationBuilder(DemoApplication.class);
        ConfigurableApplicationContext ctx = builder.run(args);

        A a = (A) ctx.getBean("a");
        B b = (B) ctx.getBean("b");

        D d = new D(a, b);
        d.method1();
        d.method2();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM