It's kinda hard to explain... Hope the question isn't vague...
you can look at the code to get the idea...
ClassA.java
public class ClassA {
@Autowired
InterA abcd;
public void dododo() {
abcd.doit();
}
}
ClassB.java
@Component
public class ClassB implements InterA {
@Override
public void doit() {
System.out.println("hoo hoo");
}
}
ClassC.java
@Component("classc")
public class ClassC {
public void doFromAbove() {
ClassA cls = new ClassA();
cls.dododo();
}
}
Interface InterA.java
public interface InterA {
public void doit();
}
Configuration ClassConfig.java (on the same package of other java class files)
@Configuration
@ComponentScan
public class ClassConfig {
}
Main Method
public static void main(String[] args) {
try(AbstractApplicationContext appctx = new AnnotationConfigApplicationContext(ClassConfig.class)) {
ClassC obj = (ClassC) appctx.getBean("classc");
obj.doFromAbove();
}
}
When I execute the main method, the Autowired field "abcd" in ClassA
didn't get injected and results in a NullPointerException
It works only when I declare ClassA
as a @Component
and get it's bean... indirect autowiring is not happening
Should I decouple ClassA
from ClassC
and make everything loosely coupled?
Is there any simple annotation that I can use to tell Spring auto inject the @Autowired field even when the object is created in a tight coupled fashion?
Note
please don't tell me to use ApplicationContext in ClassC
to create the bean of ClassA
.
Any Spring Geek who could find an answer?