4.IoC创建对象的方式

4.IoC创建对象的方式,第1张

4.IoC创建对象的方式 通过无参构造方法来创建

新建User类

package com.dream.pojo;

public class User {
    private String name;

    public User() {
        System.out.println("user无参构造方法");
    }

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

    public void show(){
        System.out.println("name="+ name );
    }
}

Spring配置


        
    

测试

@Test
    public void testUser(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User) context.getBean("user");
        user.show();
    }

可以发现在调用show方法之前,User对象已经通过无参构造初始化了

通过有参构造方法来创建
package com.dream.pojo;

public class UserT {
    private String name;

    public UserT(String name) {
        this.name = name;
    }

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

    public void show(){
        System.out.println("name="+ name );
    }
}

这里的配置bean有三种方式


        
    


        
    


        
    
@Test
    public void testUserT(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserT user = (UserT) context.getBean("userT");
        user.show();
    }

可以看到在配置文件加载的时候,其中管理的对象都已经初始化了

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5685394.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存