0

I am learning Spring framework using the online material, and implemented a simple program as below:

I am using the methodology of "Coding to interface" and this is the interface:

package com.vipin.math;

public interface MathOperations {

    public int add(int a, int b);
    public int sub(int a, int b);
}

One of the implementations that i did:

package com.vipin.math;

    public class MathOperationsImpl implements MathOperations {

    public int add(int a, int b) {

        return a+b;
    }

    public int sub(int a, int b) {

        return a-b;
    }
}

The main class which depends on this is:

package com.vipin.app;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.vipin.math.MathOperations;
import com.vipin.math.MathOperationsImpl;

public class MainApp {

    public static void main(String[] args) {

        MathOperations mathOperations;
        ApplicationContext appContext = null;
        appContext = new ClassPathXmlApplicationContext("spring.xml");
        mathOperations = appContext.getBean("mathOperationsImpl", MathOperationsImpl.class);
        System.out.println(mathOperations.add(10, 20));
    }

Now, since MainApp is dependent on MathOperations (to specific implementing class), and we doing this using getBean() on ApplicationContext.

I tried using @Resource / @Autowire instead of using getBean(), like this in Main itself:

@Resouce("MathOperationsImpl")
MathOperations mathOperations;

Also like this:

@Autowired()
@Qualifire("MathsRelated")
MathOperations mathOperations;

However, i am getting null pointer exception when i am invoking the add() method.

Isn't DI supposed to work in such scenarios?

Any clue would be appreciated.

Here is spring.xml, only relevant portions shown here

<beans 

<bean id="mathOperationsImpl" class="com.vipin.math.MathOperationsImpl">
<qualifier value="MathsRelated">
</bean>

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
CuriousMind
  • 8,301
  • 22
  • 65
  • 134

1 Answers1

0

The auto-wiring will work only if the Main class is also managed by Spring container. In other words it should be one of the Component class that can be configured, wired and managed by Spring itself.

Here the Main class is used to load the Spring container. Use some other class and define a bean in XML or use auto-wiring feature in that class that should be annotated by @Component if you are using Auto-discovery feature of Spring.

Braj
  • 46,415
  • 5
  • 60
  • 76