When a bean is created, if the bean property is not initialized and assigned a value in the bean definition in the configuration file, spring will not initialize the property by default) check is not performed. However, in many cases, bean-specific attributes must be initialized and assigned values. In spring2.x, spring uses the dependency-check attribute in bean labels to set the method for force checks. The denpendency-check attribute has four values.
<Bean id = "Ernie" class = "com. ***. "dependency-check =" NONE "> // if you do not set it, it is the default value of dependency-check in spring. No check is performed.
<Bean id = "Ernie" class = "com. ***." dependency-check = "simple"> // only check simple type attributes and set type attributes
<Bean id = "Ernie" class = "com. ***. "dependency-check =" object "> // check the reference type attributes except simple type attributes and set type attributes
<Bean id = "Ernie" class = "com. ***." dependency-check = "all"> // check all types of attributes
If the check fails, an exception org. springframework. Beans. Factory. unsatisfieddependencyexception is thrown.
After reading the above tutorial, I ran to my project to write code for testing. The following exception is thrown.
My spring-config.xml code is as follows:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="toBeCheckedBean" class="dependencycheck.ToBeCheckedBean" dependency-check="simple" /> </beans>
I found that the above Code using spring3.0 XSD (http://www.springframework.org/schema/beans/spring-beans-3.0.xsd) (used to verify the validity of the XML document, the same role as the DTD file ), the dependency-check attribute is not defined in the XSD file of spring3.0, because spring3 + has abandoned this attribute, to use this attribute, you need to use the XSD file of spring2.5.
Since spring3 does not use the dependency-check attribute, it will certainly replace it.
After checking the information, spring3 has four suggestions for replacing dependency-check:
- Use constructors (constructor injection instead of setter injection) exclusively to ensure the right properties are set.
- Use Constructor (use constructor injection instead of setter injection) to verify that a specific attribute is initialized.
- Create setters with a dedicated init method implemented.
- Use the init method to initialize the attributes of setter
- Create setters with @ required annotation when the property is required.
- Annotation @ required on setters that require forced initialization, refer to http://www.mkyong.com/spring/spring-dependency-checking-with-required-annotation/
- Use @ autowired-driven injection which also implies a required property by default.
- @ Autowired-driven injection can also be used.