·
To make Setter DI mandatory
·
we can achieve by using dependency-check attribute in <bean>
tag
·
by default dependency-check value is none (none/simple/object/all)
·
none --> it won’t call setter methods
·
Simple --> it call only primitive setters (int/string)
·
object --> it call only Secondary setters (Object)
·
all --> both primitive & Secondary Setters Injection is mandatory
·
UnsatisifiedException : cause behalf this
·
@Required --> it forces us to DI for given datatype
·
we need instantiate RequireAnnotationPostProcessor in xml bean to activate
annotation
Example
package bean;
import org.springframework.beans.factory.annotation.Required;
public class Car {
private Engine engine;
private String carname;
public Engine getEngine() {
return engine;
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public String getCarname() {
return carname;
}
@Required
public void setCarname(String carname) {
this.carname = carname;
}
public void getData(){
System.out.println(carname);
System.out.println(engine.getModel());
}
}
package bean;
public class Engine {
private int model;
public void setModel(int model) {
this.model = model;
}
public int getModel() {
return model;
}
}
package driver;
public class SpringHello {
public static void main(String[] args) {
ApplicationContext c = new ClassPathXmlApplicationContext("res/s.xml");
Car b = (Car)c.getBean("c");
b.getData();
}
}
--------------------------------------
<!DOCTYPE beans PUBLIC "-//SPRING//DTD
BEAN 2.0//EN"
<beans>
<!--
None : No need to pass any setter
and ConstructorDI, it will execute
<bean id="c" class="bean.Car"
dependency-check="none">
</bean> -->
<!-- // Simple : we must pass setter DI values */
<bean id="c" class="bean.Car"
dependency-check="simple">
<property name="carname" value="HONDA"/>
</bean>
-->
<!-- // Objects : we must pass secondry DI values
<bean id="e1" class="bean.Engine">
<property name="model"
value="2013"></property>
</bean>
<bean id="c" class="bean.Car"
dependency-check="objects">
<property name="engine" ref="e1"
></property>
</bean>
*/-->
<!-- // All : we must pass both primary and secondry DI values
*/-->
<bean id="e1"
class="bean.Engine">
<property name="model"
value="2013"></property>
</bean>
<bean id="c"
class="bean.Car" dependency-check="objects">
<property name="carname"
value="HONDA"/>
<property name="engine"
ref="e1" ></property>
</bean>
<!-- @Required : to activete
this we must instanciate RequiredAnnotationBeanPostProcessor in <bean>
tag-->
<bean class="RequiredAnnotationBeanPostProcessor"></bean>
</beans>