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

2025-10-23 03:04:00

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创建对象

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢