Spring - Annotation using Java
There are times when we don't want to write an XML file at all and want to write everything using java. And thankfully annotations comes to rescue.
Say no to application-context.xml
So far we have used 'application-context.xml' to define the beans. Now, let us convert 'application-context.xml' to a java class and see how it works.
Car class using annotation
class Car {
@Value("Hyundai")
String brand;
-- Getters and Setters --
}
The @Value("Hyundai") before the 'brand' property tells spring that 'brand' should be assigned with value 'Hyundai'.
And the replacement class for 'application-context.xml' is defined below :
@Configuration
public class JavaAppConfig {
@Bean(name="car")
public Car getCar(){
return new Car();
}
}
So, we have used @Configuration above the 'JavaAppConfig'. Which informs spring that it should be treated as a Configuration class(Or a replacement for application-context.xml).
And @Bean(name="car") before the getter method tells spring that 'Car' should be treated as a bean. Which is a perfect replacement for :
<bean name = "car" class = "Car">
<property name = "brand" value="Hyundai"/>
</bean>
Note :The @Bean annotation cannot be placed above the class name but should be placed above the getter method of a particular bean.
Finally, in the main() method we define our application code to interact with spring.
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
public static void main(String[] args) {
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(JavaAppConfig.class);
Car car = (Car)applicationContext.getBean("car");
System.out.println("The Car brand is : "+car.getBrand());
}
}
Output :
The value is : Hyundai