Overview
- In previous blog, we saw Dependency Injection in Spring using Annotation.
- Here we will see how we can do the same using Annotation but without defining Autoscan in XML.
- We will make use of @Configuration and @Bean to define configuration the same as we did for XML in above case.
Configuration Class
@Configuration
public class AppConfiguration {
@Bean
public Paint getPaint(){
return new RedPaint();
}
@Bean
public Car car(){
return new Car(getPaint()); // Injected Bean here
}
}
Car Class
public interface Vehicle {
public void getType();
public void getPaint();
}
public class Car implements Vehicle{
Paint mypaint;
Car(Paint mypaint){
System.out.println("Constructor injection called. Setting Paint");
this.mypaint = mypaint;
}
@Override
public void getType() {
System.out.println("This is a Car");
}
@Override
public void getPaint() {
mypaint.getColor();
}
}
Main Class
public class MainApp {
public static void main(String[] args) {
// load the spring configuration file
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfiguration.class);
System.out.println("Loading Config Done");
Vehicle veh = context.getBean("car", Vehicle.class);
veh.getPaint();
veh.getType();
context.close();
}
}
OUTPUT:
Aug 05, 2018 10:41:32 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@368102c8: startup date [Sun Aug 05 22:41:32 IST 2018]; root of context hierarchy
RedPaint Constructor called
Constructor injection called. Setting Paint
Loading Config Done
I will paint Red color
This is a Car
Aug 05, 2018 10:41:33 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@368102c8: startup date [Sun Aug 05 22:41:32 IST 2018]; root of context hierarchy
Explanation
- Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.
- The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.
- In the main class, we are using AnnotationConfigApplicationContext instead of ClassPathXmlApplicationContext as done for XML based injection.
- AnnotationConfigApplicationContext is also an implementation of ApplicationContext.
- We are passing AppConfiguration.class in AnnotationConfigApplicationContext Object to tell spring about our configuration class.
You can get the code used above here. Just look for com.main.spring.alljava package.
0 Comments