In most cases, you would like to check if particular properties have been set, but not all properties of certain types. For this Spring provides @Required annotation in order to check a particular property. It works in Java1.5 and above versions only.
Let's use @Required annotation in application.AccountService.java
- package org.myjavaswtech.service;
-
- import org.myjavaswtech.dao.AccountDAO;
- import org.springframework.beans.factory.annotation.Required;
-
- public class AccountService {
-
- private AccountDAO accountDao;
-
- @Required
- public void setAccountDao(AccountDAO accountDao) {
- this.accountDao = accountDao;
- }
- public void transferFund(String acNo, String benAcNo, double amount){
- System.out.println("Call to Account DAO");
- accountDao.transferFund(acNo, benAcNo, amount);
- }
- }
Inorder to work @Required Annotation, you need to register RequiredAnnotationBeanPostProcessor instance in the IoC container.
RequiredAnnotationBeanPostProcessor is a Spring bean post processor that checks if all the bean properties with the @Required annotation have been set.
beans.xml
Now Run the application: You'll get the following exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountService' defined in class path resource [beans.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'accountDao' is required for bean 'accountService'.
Spring2.5 and Above : <context:annotation-config>
In Spring2.5 and above versions, <context:annotation-config> is used in IOC container instead of RequiredAnnotationBeanPostProcessor. If you use <context:annotation-config> element in your bean configuration file, and a RequiredAnnotationBeanPostProcessor instance will automatically get registered.
beans.xml
In the above configuration we used context namespace and schema location.
Now Run the application: You'll get the following exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountService' defined in class path resource [beans.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'accountDao' is required for bean 'accountService'.