Spring实例参考03-通过构造方法创建对象-创新互联-成都快上网建站

Spring实例参考03-通过构造方法创建对象-创新互联

本文供以下文章参考使用:

在石景山等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供成都网站建设、网站建设 网站设计制作按需网站策划,公司网站建设,企业网站建设,品牌网站建设,全网整合营销推广,外贸网站制作,石景山网站建设费用合理。

Spring笔记https://blog.csdn.net/qq_34378496/article/details/128095043java对象:

package com.evenif.bean;

public class Index {

    private int id;
    private String name;
    
    //无参构造方法
    public Index() {
        System.out.println("create Index class");
    }
    //两个参数的构造方法
    public Index(int id, String name) {
        this.id = id;
        this.name = name;
        System.out.println("create Index class with params");
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Index{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

beans.xml配置文件:

测试主函数

package com.evenif;

import com.evenif.bean.Index;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        //注意这个xml文件位置要放对
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Index index01 = (Index) context.getBean("index01");
        System.out.println(index01);
        Index index02 = (Index) context.getBean("index02");
        System.out.println(index02);
        Index index04 = (Index) context.getBean("index04");
        System.out.println(index04);
        Index index06 = (Index) context.getBean("index06");
        System.out.println(index06);
    }
}
//执行结果:注意,即使不获取index01或index02依然会调用两个构造方法,
//当执行 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); 时对象就创建了。
//        create Index class
//        create Index class with params
//        create Index class with params
//        create Index class with params
//        Index{id=0, name='ip01'}
//        Index{id=1, name='ca02'}
//        Index{id=4, name='ca04'}
//        Index{id=6, name='ca06'}

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


文章标题:Spring实例参考03-通过构造方法创建对象-创新互联
文章位置:http://kswjz.com/article/dhcpeo.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流