Spring入门实例:用Spring创建对象

 时间:2026-02-14 02:08:59

1、新建一个domain对象实例:Department。

package com.gwolf.springmvc.domain;

public class Department {

        private Integer id;

        private String departmentName;

        public Department() {

                

        }

        

        public Department(int i, String string) {

                this.id = i;

                this.departmentName = string;

        }

        public Integer getId() {

                return id;

        }

        public void setId(Integer id) {

                this.id = id;

        }

        public String getDepartmentName() {

                return departmentName;

        }

        public void setDepartmentName(String departmentName) {

                this.departmentName = departmentName;

        }

        @Override

        public String toString() {

                return "Department [id=" + id + ", departmentName=" + departmentName

                                + "]";

        }

        

}

Spring入门实例:用Spring创建对象

2、在java类路径下新建一个文件:applicationContext.xml。

Spring入门实例:用Spring创建对象

3、在applicationContext.xml文件中声明Department实例。

<?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">

        <bean id="department" class = "com.gwolf.springmvc.domain.Department">

                <property name="departmentName" value="技术部"></property>

        </bean>

        

</beans>

Spring入门实例:用Spring创建对象

4、在Main类中初始化Spring的IOC容器对象。

ApplicationContext applicationContext = 

              new ClassPathXmlApplicationContext("applicationContext.xml");

Spring入门实例:用Spring创建对象

5、从IOC容器中获取Bean实例:Spring将调用构造器初始化Bean方法。

ApplicationContext applicationContext = 

           new ClassPathXmlApplicationContext("applicationContext.xml");

Department department = (Department)applicationContext.getBean("department");

Spring入门实例:用Spring创建对象

6、调用Bean对象的方法。

Spring入门实例:用Spring创建对象

  • 花生棒+树莓派端口映射搭建Web网站
  • win10 1903新bug移动宽带无法正常WiFi连接
  • linux下telnet安装与使用
  • 如何让笔记本电脑变成一个路由器
  • Xenserver中如何关闭虚拟机
  • 热门搜索
    美术手抄报 安全的手抄报内容 七彩童年手抄报图片 手抄报装饰简单又漂亮 感恩老师的手抄报图片 古诗词手抄报内容 成长足迹手抄报资料 手抄报装饰简笔画 民族传统文化手抄报 手抄报图案大全