Spring02:构造器注入

本文演示了如何在Spring中通过XML配置文件创建并注入属性的Bean。首先引入了Spring和JUnit的依赖,然后定义了一个Dog实体类。接着在XML配置文件中使用`<constructor-arg>`标签设置了Dog的构造器参数。最后,在测试类中,通过`ClassPathXmlApplicationContext`获取并打印了已注入属性的Dog对象。
摘要由CSDN通过智能技术生成

目的:使用spring得到一个已经注入属性的对象

  1. 导入依赖

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.9</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.1</version>
        <scope>test</scope>
    </dependency>
    
  2. 写实体类

    package com.xxx.pojo;
    
    public class Dog {
        String name;
        int age;
    
        public Dog(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "Dog{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    
    
  3. 写xml文件

    constructor-arg标签可以使用三种方式

    name/type/index

    也就是名字,参数类型,索引

    当然如果参数类型一样则玩不转了

    <?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标签-->
        <bean id="dog" class="com.xxx.pojo.Dog">
            <constructor-arg name="age" value="3"/>
            <constructor-arg name="name" value="二狗子"/>
        </bean>
    
    </beans>
    
  4. 写测试类

    import com.xxx.pojo.Dog;
    import org.junit.Test;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MyTest {
        @Test
        public void test01() {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
            Dog dog = context.getBean("dog", Dog.class);
            System.out.println(dog);
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值