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:
@SpringBootApplication
annotation and having the main
methodThis 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.