使用@required注解完成依赖检查

it2024-08-10  78

使用@required注解完成依赖检查:

即在对象属性的set方法上添加 @required后,若 <bean>配置中不为该属性赋值,运行会报错。

第一步:

package com.xuzhiwen.spring91; import org.springframework.beans.factory.annotation.Required; public class RequiredTest { private String name; private String hobby; @Required public void setName(String name) { this.name = name; } @Required public void setHobby(String hobby) { this.hobby = hobby; } @Override public String toString() { return "RequiredTest [name=" + name + ", hobby=" + hobby + "]"; } }

第二步:

required.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="requiredTest" class="com.xuzhiwen.spring91.RequiredTest"> <property name="name" value="tom" /> <property name="hobby" value="tom" /> </bean> </beans>

这样才能保证运行不出错。

 

注:看文档中需要配置扫描

<context:annotation-config /> 但是我试过,没陪好像也是可以的,不知道为何?

转载于:https://www.cnblogs.com/beibidewomen/p/7411709.html

最新回复(0)