SpringIOC创建对象的方式

无参构造创建对象

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.xml


        

测试类

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    //在执行getBean的时候, user已经创建好了 , 通过无参构造
    User user = applicationContext.getBean("user", User.class);
    //调用对象的方法 .
    user.show();
}

有参构造方法创建对象

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 );
    }
}

spring.xml的三种方式

根据index下标设置


        

根据参数名设置


        

根据类型设置


        

测试类

@Test
public void testT(){
    ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    UserT user = context.getBean("userT",UserT.class);
    user.show();
}

你可能感兴趣的:(java,spring)