zoukankan      html  css  js  c++  java
  • Spring IOC容器创建对象的方式

    一、无参构造函数创建                                                                           

    我们用Spring创建Student类的对象

    Student类声明如下

    package com.study.spring;
    public class Student {
        private String name;
        private int age;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString() {
            return "name:"+name+"
    "+"age:"+age;
        }
    
    }

    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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="student" class="com.study.spring.Student">
            <property name="name" value="尼古拉斯赵四"></property>
            <property name="age" value="37"></property>
        </bean>
    </beans>

    使用Bean工厂初始化,测试代码如下

    package com.study.spring;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Test {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("\com\study\spring\beans.xml");
            Student stu = (Student) context.getBean("student");
            System.out.println(stu);
    
        }
    }

    执行结果如下:

    name:尼古拉斯赵四
    age:37

    总结

    <bean id="student" class="com.study.spring.Student">
            <property name="name" value="尼古拉斯赵四"></property>
            <property name="age" value="37"></property>
        </bean>

    配置一个bean,id为代码中取得bean的代号,不可以重复,class为类的类型,包含完整的包名。property 指的是类中的属性 name为属性名称 ,value是给此属性赋的值。

    值得注意的是,property 中的name属性的值对应的是类中属性的set方法,省略了前缀set,如本文中设置name=“age”实际上指的是给setAge方法传递一个参数的配置,所以命名应该按照约定,做到规范和命名。若没有set方法就无法实现实例化。直接报错。

  • 相关阅读:
    [转]如何选购塑料水杯(塑料口杯、茶杯)
    【转】在sqlserver下增加MYSQL的链接服务器,实现分布式数据库开发第一步
    MySql: 查看当前登录用户,当前数据库
    python import, from xx import yy
    python class metaclass instance
    git: fatal: Not a git repository (or any of the parent directories): .git
    Python flask 基于 Flask 提供 RESTful Web 服务
    Python flask @app.route
    MySql: log 位置
    MySql: 忘记root密码
  • 原文地址:https://www.cnblogs.com/doublejun/p/5384586.html
Copyright © 2011-2022 走看看