How to define a custom Required-style annotation for dependency checking?
Another alternative way of checking the dependencies of a spring bean is by creating a custom annotation of the same style as
@Required annotation. This annotation is equivalent to @Required annotation. In case, if you are migrating your code to spring, if you have
used few custorm annotations to check dependencies, this approach will be very useful.
Here is the @Mandatory custom annotation:
package com.java2novice.utils;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Mandatory {
}
|
We replaced @Required annotation with @Mandatory annotation:
package com.java2novice.beans;
import com.java2novice.utils.Mandatory;
public class PaymentGateway {
private String client;
private Order order;
@Mandatory
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, we declared our custom annotation @Mandatory with RequiredAnnotationBeanPostProcessor class.
<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">
<property name="requiredAnnotationType" value="com.java2novice.utils.Mandatory"/>
</bean>
<bean id="paymentGateway" class="com.java2novice.beans.PaymentGateway" />
</beans>
|
Finally the demo class, since we didn't pass order object to PaymentGateway class, we should expect exception here:
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());
}
}
|
|