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"/>