0

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?

Searene
  • 25,920
  • 39
  • 129
  • 186

1 Answers1

-3

You declared oracleClient static variable is incorrectly.@AutoWired is equivalent of a setter method, how you can make Spring to do a static setter method.so you should remove the static keyword, and it should be ok.

Crabime
  • 644
  • 11
  • 27
  • No. I removed the `static` keyword, and it still didn't work. Do I need to set a setter/getter method somewhere? – Searene Aug 14 '16 at 02:06
  • oh man,are you kidding me.do you know @Autowired usage? it means you put the autowired element to the spring container.after you push it to the container you still need to get its instance from the container in the main method. – Crabime Aug 14 '16 at 03:08