首页 > 代码库 > Spring 简单的配置和操作 ( 创建实体类, 配置XML文件, 调试 )

Spring 简单的配置和操作 ( 创建实体类, 配置XML文件, 调试 )

< 1 > 实体类 Person

package java_spring.modle;

/**
 * 一个实体类( Person )
 */
public class Person {

    private int userId;
    private String userName;
    private String userAge;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

    @Override
    public String toString() {
        return "Person [userId=" + userId + ", userName=" + userName + ", userAge=" + userAge + "]";
    }

}

< 2 > 配置文件 spring.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"
>
    <!-- 通过 spring 配置一个 Person 实力化类 PersonOne 并赋值 -->
    <bean id="personOne" class="java_spring.modle.Person">
        <property name="userId" value="1"></property>
        <property name="userName" value="张三丰"></property>
        <property name="userAge" value="男"></property>
    </bean>
</beans> 

< 3 > 测试类 TestOne

package java_spring.a_main;

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

import java_spring.modle.Person;

public class TestOne {

    public static void main(String[] args) {
        // 获取 spring 的 IOC 容器对象, 参数是配置文件相对于 src 的路径
        ApplicationContext ac = new ClassPathXmlApplicationContext("java_spring/config/spring.xml");
        
        // 通过容器对象获取配置好的 javabean 对象, 参数是配置文件中的  id
        Person personOne = (Person) ac.getBean("personOne");
        System.out.println(personOne);
    }

}

 

 

 

Spring 简单的配置和操作 ( 创建实体类, 配置XML文件, 调试 )