Spring5依赖注入(DI)拓展(pc命名空间)注入实现收录

Spring5依赖注入(DI)拓展(pc命名空间)注入实现收录

命名空间pc注入

User.java

package com.lanyy.pojo;

public class User {
    private String name;
    private int age;
    // 引入无参构造器 确保p命名空间注入
    // 引入有参构造器 确保c命名空间注入
    public User() {
    }
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

p与c命名空间注入

p命名空间导入约束 : xmlns:p="http://www.springframework.org/schema/p"

<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->

c命名空间导入约束 : xmlns:c="http://www.springframework.org/schema/c"

<!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--    <bean id="user" class="com.lanyy.pojo.User">-->
<!--        <property name="name" value="lanyy"/>"-->
<!--    </bean>-->

<!--  p命名空间注入,可以直接注入属性的值:property 无参构造 -->
    <bean id="user" class="com.lanyy.pojo.User" p:name="懒羊羊" p:age="18"/>
<!--  c命名空间注入,可以直接注入构造器:constructor-args 有参构造 -->
    <bean id="users" class="com.lanyy.pojo.User"  c:age="18" c:name="lanyy699"/>
</beans>

Test类编写

    @Test
    public void test2() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        Object user = context.getBean("user");
        System.out.println(user);
    }
    @Test
    public void test3() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        Object users = context.getBean("users");
        System.out.println(users);
    }

测试运行

 users = context.getBean("users");
         System.out.println(users);
    	 }

在这里插入图片描述

了解更多知识请戳下:

@Author:懒羊羊

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会撸代码的懒羊羊

打赏5元,买杯咖啡醒,继续创作

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值