spring(5)c命名和p命名空间注入

搭建环境        ​spring(4)icon-default.png?t=M4ADhttps://blog.csdn.net/qq_47525487/article/details/124754079?spm=1001.2014.3001.5502

p命名空间注入

在pojo包下新建User类,resource包下新建userbeans.xml,并按如下配置

package com.kuang.pojo;
public class User {
    private String name;
    private int 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 +
                '}';
    }
}



    
    

在外层pom.xml中导入junit包,记住要确保Maven依赖项里有文件

        
            junit
            junit
            4.12
            test
        

修改MyTest类

import com.kuang.pojo.Student;
import com.kuang.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        //后面显示了类型就不用去强转了
        User user = context.getBean("user",User.class);
        System.out.println(user);
    }
}

结果

spring(5)c命名和p命名空间注入_第1张图片

C命名

User类中添加有参,无参 

userbeans.xml中添加


    

MyTest类中的

        User user = context.getBean("user",User.class);

改为

        User user = context.getBean("user2",User.class);

结果

spring(5)c命名和p命名空间注入_第2张图片

 

你可能感兴趣的:(spring,java,后端)