0
点赞
收藏
分享

微信扫一扫

p命名标签注入和c命名标签注入

dsysama 2022-01-10 阅读 48

首先使用p或c标签注入需要导入约束

在xml文件上方加入

 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:c="http://www.springframework.org/schema/c"

p命名标签可以给属性传值,相当于property

c命名标签可以给参数传值,相当于constructor-arg

实体类中写入无参构造和有参构造

    public Student() {
    }

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

配置文件中写入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       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="student" class="pojo.Student" p:name="李佳琪"/>
    <bean id="student1" class="pojo.Student" c:name="李佳琪1"/>
</beans>

测试类

    @Test
    public void myTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        Student student1 = context.getBean("student1", Student.class);
        System.out.println(student);
        System.out.println(student1);
    }

测试结果与预想结果一致

举报

相关推荐

0 条评论