zoukankan      html  css  js  c++  java
  • SpringFramework|@Required的使用

    @Required的使用

    前述

    Java: 1.8

    Maven: 3

    SpringFramework版本以及各组件成员: 5.1.1.RELEASE

    • spring-context
    • spring-core
    • spring-beans

    @Required注释适用于bean属性setter方法, 再通过在bean定义或通过自动装配一个明确的属性值:

    Required意为"需要", 它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。

    public class SimpleMovieLister {
    
        private MovieFinder movieFinder;
    
        @Required
        public void setMovieFinder(MovieFinder movieFinder) {
            this.movieFinder = movieFinder;
        }
    
        // ...
    }
    

    @Required将在以后的版本弃用.

    示例

    TestBean.java - 一个Bean(这不是一个规范的JavaBean, 顺口而叫的):

    package noioo;
    
    
    import org.springframework.beans.factory.annotation.Required;
    
    public class TestBean {
    
        private String theValue;
    
        public String getTheValue() {
            return theValue;
        }
    
        @Required  // 用在set上面
        public void setTheValue(String theValue) {
            this.theValue = theValue;
        }
    }
    
    

    spring-beans.xml中启用注解.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:content="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <content:annotation-config/>
    
        <bean id="testBean" class="noioo.TestBean">
            <property name="theValue" value="Hello, World"/>
        </bean>
    </beans>
    

    执行者 - Runner.java

    package noioo;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Runner {
    
        public static void main(String[] args){
            ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
            TestBean testBean = (TestBean)context.getBean("testBean");
            System.out.println(testBean.getTheValue());
        }
    }
    

    执行结果

    Hello, World
    
    Process finished with exit code 0
    
  • 相关阅读:
    Android实现App版本自动更新
    Android EditText+ListPopupWindow实现可编辑的下拉列表
    Android 侧滑面板的实现(DragLayout)
    android之SlideMenu双向滑动
    Android 从无到有打造一个炫酷的进度条效果
    Android 自定义View修炼-仿360手机卫士波浪球进度的实现
    TabLayout禁止选择
    Metasploit的攻击实例讲解----ms10_046快捷方式图标漏洞
    PowerDesigner 16.5的下载安装破解注册(图文详解)
    Metasploit的armitage初步使用
  • 原文地址:https://www.cnblogs.com/shwo/p/9863487.html
Copyright © 2011-2022 走看看