I'm using Spring
and @Autowired
to inject an instance into my main class, but I failed.
I have an interface named OracleClient
, a class named OracleClientImpl
which implements the former interface, the contents of them are as follows.
Oracleclient
public interface OracleClient {
void doSomething();
}
OracleClientImpl
@Service("oracleClient")
public class OracleClientImpl implements OracleClient {
@Override
public void doSomething() {
System.out.println("doSomething");
}
}
And I've added these lines in my Spring configuration file:
<context:annotation-config/>
<context:component-scan base-package="com.company" />
My main class looks like this:
public class App {
@Autowired
private static OracleClient oracleClient;
public static void main(String[] args) throws IOException {
ApplicationContext cxt = new ClassPathXmlApplicationContext("spring-config.xml");
oracleClient.doSomething();
}
}
It doesn't work, oracleClient
is null
in this case. But if I try to get the bean using code instead of @Autowired
, oracleClient
would be injected successfully.
public class App {
public static void main(String[] args) throws IOException {
ApplicationContext cxt = new ClassPathXmlApplicationContext("spring-config.xml");
OracleClient oracleClient = (OracleClientImpl) cxt.getBean("oracleClient");
oracleClient.doSomething();
}
}
I'm wondering why. And is there a way to make it work via @Autowired
?