zoukankan      html  css  js  c++  java
  • 为什么ioc使用构造方法去创建对象

    为什么ioc使用构造方法去创建对象

    public class User {
      private String name;
      // 将无参数构造方法显式地写出来
      public User(){
        System.out.println("无参数构造方法执行。。。");
     }
      public void setName(String name){
    this.name = name;
     }
      public void show(){
        System.out.println("name:" + name);
     }
    }

    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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 无参数构造方法 -->
      <bean id="user" class="com.ping.pojo.User">
        <property name="name" value="小王"></property>
      </bean>
    </beans>

    测试类:

    package com.ping.dao;
    import com.ping.pojo.User;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    public class UserTest {
      public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new
    ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user");
        user.show();
        System.out.println(user);
     }
    }
    /* 运行结果:
          无参数构造方法执行。。。
          name:小王
          com.ping.pojo.User@13805618
    */
    结合上述运行结果和debug,可以发现,在调用show方法之前,User对象已经通过无参构造初始化
    了!对象初始化之后,类里面方法属性都在对象里面


    需要通过构造方法获得对象,
    User user=(User) context.getbean("user");
    对象可以调用类里面的属性,方法;
    user.属性;
    user.show();

  • 相关阅读:
    poj 1200 crasy search
    cdoj 1092 韩爷的梦
    fzu 2257 saya的小熊饼干
    zoj 3950 how many nines
    zoj 3963 heap partion
    fzu 2256 迷宫
    fzu 2253 salty fish
    hdu 2473 Junk-Mail Filter
    codeforces 129B students and shoes
    hdu 3367 Pseudoforest
  • 原文地址:https://www.cnblogs.com/wwwsss/p/13863703.html
Copyright © 2011-2022 走看看