In a pure object-oriented sense we are calling a method of an object (Target object). That method has some code which is already in it. Aspect code has to run whenever we call this target method. How is it possible that some other code which is in some other class in some other method runs when we called this method, how is it even possible in a pure object-oriented paradigm.
It’s not actually possible. Aspect oriented programming is a completely different type of programming and what we do in Spring is we use some of the object oriented concepts to achieve aspect oriented programming. The way Spring uses these concepts is using a proxy.
We know proxy as a design pattern so what we do is instead of making a call to Class A, we make a call Class B and Class B internally makes a call to Class A but then it also adds some additional functionalities. This is something that Spring is doing behind the scenes for us.
Let’s try creating our own FactoryService class for having our own getBean() method:
public class FactoryService {
public Object getBean(String beanType) {
if(beanType.equals("Bicycle")) return new Bicycle();
if(beanType.equals("Car")) return new Car();
if(beanType.equals("Truck")) return new Truck();
return null;
}
}
Instead of using the:
ApplicationContext ctx = new AnnotationConfigApplicationContext(SomeConfiguration.class);
SomeClass sc = (SomeClass) ctx.getBean("someClass");
we are going to create a FactoryService instance and use that to get a bean.
Continue reading →