Issue
So I try to inject an interface implemention through a field. But can't figure it out why it's null.
Package
com.a
Interfacex
com.b
Interfaceximpl
Interfacex.java
public interface Interfacex {
void doA ();
}
Interfaceximpl.java
@Component
public class Interfaceximpl implements interfacex {
@Override
void doA(){
// do something
}
}
Main.java
public class Main {
@Autowired
Interfacex interfacex;
public static void main (String args[]){ //....}
}
This interfacex seems to be null.
@Configuration
@ComponentScan("com")
public class AppConfig { // nothing here}
There is no such setter injection in my case. I just inject the interfacex with @Autowired. Why is it null?.
Solution
Are you really placing the @Autowired
on the field of the main class or its just an illustration? If you do - it won't work because the class on which @Autowired can happen must be by itself managed by Spring. And in this case its obviously not, because its a special class - an entry point of the application...
I suggest to use something like this instead:
@Component
public class EntryPoint {
@Autowired
Interfacex interfacex;
public void foo() {
// interfacex shouldn't be null
// because everything is managed by spring now
interfacex.doA();
}
}
public class Main {
public static void main(..) {
ApplicationContext ctx = ...
EntryPoint ep = ctx.getBean(EntryPoint.class);
ep.foo();
}
}
Answered By - Mark Bramnik
Answer Checked By - Gilberto Lyons (JavaFixing Admin)