• Spring入门---示例三,Spring IOC控制反转之依赖注入【第一天】


    注意:本示例是通过applicationContext.xml进行bean的注入初始化赋值。即:

    applicationContext.xml--->bean->Test取值

    Inversion of Control(控制反转),也叫Dependency InJection(依赖注入)

    控制反转的基本概念:

    不直接创建对象,但是描述创建他们的方式。在工程中使用Bean时,由Spring容器创建Bean的实例。在代码中不直接与对象和服务连接,但要在配置文件中描述哪一个组件需要哪一项服务。

    一、依赖注入:

    Spring注入【又称依赖注入DI】的目的是为其中bean的属性赋值。

    1、通过Setter方法(一般属性赋值,即基本类型赋值示例)。

    (1) 、编写JavaBean

    package test3.ioc;

    public class User {

    private String uname,ubirth;

    private int id;

    public String getUname() {

    return uname;

    }

    public void setUname(String uname) {

    this.uname = uname;

    }

    public String getUbirth() {

    return ubirth;

    }

    public void setUbirth(String ubirth) {

    this.ubirth = ubirth;

    }

    public int getId() {

    return id;

    }

    public void setId(int id) {

    this.id = id;

    }

    }

    (2) 、在配置文件中注入属性的初始值。

     <!-- 配置通过setter注入属性的初始值 -->

     <bean id="user" class="test3.ioc.User">

       <property name="uname" value="zhangsan"></property>

       <property name="ubirth" value="2019-01-10"></property>

       <property name="id" value="123"></property>

     </bean>

    (3) 、测试:

    package test3;

    import org.springframework.beans.factory.BeanFactory;

    import org.springframework.context.support.ClassPathXmlApplicationContext;

    import test3.ioc.User;

    public class Test {

    public static void main(String[] args) {

    @SuppressWarnings("resource")

    BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");

    User user = (User)factory.getBean("user");

    //获取初始值

    System.out.println(user.getId());

    }

    }

    总结:通过以上方法,可以延伸思考一般对象的注入、构造函数的注入、集合与数组类型的注入。

  • 相关阅读:
    free命令中buffers和caches的区别
    ubuntu14.0安装ITK的步骤
    Ubuntu服务器上相关软件或应用时常打不开的问题
    机器学习之训练集_验证集_测试集
    VS C++ 并发编程
    Matlab保存uint16格式文件的相关注意事项
    OpenCV中的SVM参数优化
    caffe之solver.prototxt文件参数设置
    FY21 Microsoft Inspire Online Sessions Journey Guidance
    Azure Function Runtime版本和IP输出格式问题
  • 原文地址:https://www.cnblogs.com/ciscolee/p/10931254.html
Copyright © 2020-2023  润新知