java spring IOC Bean管理操作(xml P名称空间注入)

首先 我们来写一个基本的 通过xml的set属性注入
首先创建一个项目 然后引入 spring 最基本的几个依赖包
在这里插入图片描述
src下 下有一个 gettingStarted 包 下面有一个 user类
代码如下

package gettingStarted;

public class user {
    
    
    public String name;
    public int age;

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

    public void setAge(int age){
    
    
        this.age = age;
    }
    public int getAge(){
    
    
        return age;
    }
}

配置文件是src下的 bean.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">
    <!-- user类的对象创建 -->
    <bean id = "user" class = "gettingStarted.user">
        <property name="name" value = "小猫猫"></property>
        <property name="age" value = "13"></property>
    </bean>
</beans>

对应找到gettingStarted下的 user类 创建对象 通过property给两个set方法传递值

gettingStarted 下的text测试类 代码如下

package gettingStarted;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class text {
    
    
    public static void main(String args[]) {
    
    
        //获取配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        user user = context.getBean("user",user.class);
        System.out.println(user.getName());
        System.out.println(user.getAge());
    }
}

通过反射创建类对象 然后用get方法获取属性值 看看有没有问题
运行结果如下
在这里插入图片描述
这样 一个最基本的案例就做出来了

但是 大家会不会感觉 一个属性 配置文件搞一个property太麻烦了
其实可以简化的
这就要说到 我们的 P名称空间注入

我们修改 bean.xml配置文件 将xmlns的一行整个复制出来

然后将 xmlns改为 xmlns:p 将等于的 最后的beans换成p
在这里插入图片描述
然后 我们可以将整个bean标签修改成这样

<bean id = "user" class = "gettingStarted.user" p:name = "小猫猫" p:age = "13"></bean>

整体上说 就是直接写在bean标签上 格式是 p:属性名 = “需要注入的值”

最后 我们bean.xml下的代码是这样的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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">
    <!-- user类的对象创建 -->
    <bean id = "user" class = "gettingStarted.user" p:name = "小猫猫" p:age = "13"></bean>
</beans>

运行结果如下
在这里插入图片描述
也是没有任何问题

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/128743600
今日推荐