Spring bean @Required注解作用详解

作用

@Required注解作用于Beansetter方法上,用于检查一个Bean的属性的值在配置期间是否被赋予或设置(populated)

配置

使用隐式地注册RequiredAnnotationBeanPostProcessor,使@Required注解生效


<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.xsd"
       default-lazy-init="true">

    <context:annotation-config/>

    <bean id="resultMessage" class="com.jake.ResultMessage">
        <property name="code" value="001" />
    bean>
beans>

ResultMessage

codemessagesetter方法上加上@Required注解

public class ResultMessage {

    private String code;

    private String message;

    public String getCode() {
        return code;
    }

    @Required
    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    @Required
    public void setMessage(String message) {
        this.message = message;
    }
}

测试

@Controller
public class Test{

    @Autowired
    private ResultMessage message;

    @RequestMapping("/testRequired")
    public String testRequired(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println(message);
    }
}

结果

此时访问testRequired,可以看到,报BeanInitializationException异常。

org.springframework.beans.factory.BeanInitializationException: Properties 'message' are required for bean 'resultMessage'

参考资料

https://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/beans.html#beans-required-annotation

你可能感兴趣的:(Spring,spring,bean,required,注解)