Spring dependency checking with @Required annotation
Sometimes, we need to make sure that all the required dependencies are set to the spring bean. Spring provides
@Required annotation to check spring dependencies. If the required dependencies are not set, then it throws BeanInitializationException.
In this example, the PaymentGateway class has a dependency called Order class. In order to check dependenty set @Required annotation to
setOrder() method as shown below:
package com.java2novice.beans;
import org.springframework.beans.factory.annotation.Required;
public class PaymentGateway {
private String client;
private Order order;
@Required
public void setOrder(Order ord){
this.order = ord;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public Order getOrder() {
return order;
}
public void processOrder(){
System.out.println("Processing order: "+order.getItem());
}
}
|
Here is the xml based configuration, make sure that you are adding <context:annotation-config /> tag and yu are registering
RequiredAnnotationBeanPostProcessor in your spring configurations to enable @Required annotation.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean
class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<bean id="paymentGateway" class="com.java2novice.beans.PaymentGateway" />
</beans>
|
Here is the spring demo class, since we didnot provide the required dependencies, we must expect exception:
package com.java2novice.test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.beans.PaymentGateway;
public class SpringDemo {
public static void main(String a[]){
String confFile = "applicationContext.xml";
ConfigurableApplicationContext context
= new ClassPathXmlApplicationContext(confFile);
PaymentGateway myEmp = (PaymentGateway) context.getBean("paymentGateway");
System.out.println(myEmp.toString());
}
}
|
|