0
点赞
收藏
分享

微信扫一扫

Spring学习笔记(二)。IOC无参创建对象方式,IOC有参创建对象方式

GhostInMatrix 2022-02-02 阅读 80

文章目录

1、IOC创建对象方式

1.1.通过无参构造方法来创建

  1. User.java
public class User {
    private String name;

    public User(){
        System.out.println("User的无参构造");
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("name:"+name);
    }
}
  1. applicationContext.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="user" class="com.xxc.pojo.User">
        <property name="name" value="江南"/>
    </bean>
</beans>
  1. 测试
public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = (User) context.getBean("user");
        user.show();
    }
}

在这里插入图片描述

1.2.通过有参构造方法来创建

  1. userT.java
public class UserT {
    private String name;
    public UserT(){
        System.out.println("UserT的无参构造");
    }
    public UserT(String name){
        this.name = name;
        System.out.println("UserT的有参构造");
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("name:"+name);
    }
}
  1. applicationContext.xml有三种方法
<!-- 第一种根据index参数下标设置 -->
<bean id="userT" class="com.xxc.pojo.UserT">
    <!-- index指构造方法 , 下标从0开始 -->
    <constructor-arg index="0" value="江南1"/>
</bean>
<!-- 第二种根据参数类型设置 -->
<bean id="userT" class="com.xxc.pojo.UserT">
    <constructor-arg type="java.lang.String" value="江南2"/>
</bean>
<!-- 第三种根据参数名字设置 -->
<bean id="userT" class="com.xxc.pojo.UserT">
    <!-- name指参数名 -->
    <constructor-arg name="name" value="江南3"/>
</bean>
  1. 测试
public class MyTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserT user = (UserT) context.getBean("userT");
        user.show();
    }
}

在这里插入图片描述

举报

相关推荐

0 条评论