spring的IoC(Inversion of Control)4——p和c命名空间

在前面的文章中,提到了在Spring中注入有构造器注入和Set方式注入,并且均对这两种注入进行了简单的案例实践。这里对于以上的两种注入方式,有两种比较简单的写法。

1. 对于构造器注入

在官方文档中叫c-namespace,对应前面学过的构造器注入方式。官方文档地址:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-c-namespace
首先需要引入约束xmlns:c="http://www.springframework.org/schema/c",然后使用c:使用,如,User.java中定义:

private int age;
private String name;

public User() {
    
    
}

public User(int age, String name) {
    
    
    this.age = age;
    this.name = name;
}

并生成对应的getsettoString方法,然后,我们在beans.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"
       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="weizu" class="com.weizu.pojo.User" c:age="12" c:name="战三"></bean>
</beans>

测试:

public class myTest {
    
    

    @Test
    public void Test(){
    
    
        // create and configure beans
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User userService = (User) context.getBean("weizu");
        System.out.println(userService.toString());
    }
}

在这里插入图片描述

2. Set版本

使用p-namespace来进行简化。set属性注入默认使用无参构造函数,然后使用set方法来进行值的注入。地址:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-p-namespace。类似的,需要先引入约束:xmlns:p="http://www.springframework.org/schema/p",然后p:。使用案例:

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="weizu" class="com.weizu.pojo.User" p:age="12" p:name="战三"></bean>
</beans>

测试函数不变,结果:
在这里插入图片描述


视频地址:https://www.bilibili.com/video/BV1WE411d7Dv?p=10

猜你喜欢

转载自blog.csdn.net/qq_26460841/article/details/115050585