spring对容器ioc的运用

  • 时间:
  • 来源:互联网
  • 文章标签:

项目结构如下
在这里插入图片描述
创建实体类Person

package springs;

public class Person {
		private String lastName;
		private Integer age;
		private String gender;
		private String email;
		/**
		 * @return the lastName
		 */
		public String getLastName() {
			return lastName;
		}
		/**
		 * @param lastName the lastName to set
		 */
		public void setLastName(String lastName) {
			this.lastName = lastName;
		}
		/**
		 * @return the age
		 */
		public Integer getAge() {
			return age;
		}
		/**
		 * @param age the age to set
		 */
		public void setAge(Integer age) {
			this.age = age;
		}
		/**
		 * @return the gender
		 */
		public String getGender() {
			return gender;
		}
		/**
		 * @param gender the gender to set
		 */
		public void setGender(String gender) {
			this.gender = gender;
		}
		/**
		 * @return the email
		 */
		public String getEmail() {
			return email;
		}
		/**
		 * @param email the email to set
		 */
		public void setEmail(String email) {
			this.email = email;
		}
		/* (non-Javadoc)
		 * @see java.lang.Object#toString()
		 */
		@Override
		public String toString() {
			return "person [lastName=" + lastName + ", age=" + age + ", gender=" + gender + ", email=" + email + "]";
		}
		
}

创建配置文件ioc.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
   	<bean id="person01" class="springs.Person">
   		<property name="lastName" value="zhangsan"></property>
   		<property name="age" value="18"></property>
   		<property name="email" value="zhangsan"></property>
   		<property name="gender" value="nan"></property>
   	</bean>
</beans>

测试类,测试是否正确

package test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import springs.Person;

public class TestSpring {
		@Test
		public void test() {
			//获取ioc容器对象,以及配置文件的路径
			ApplicationContext ioc=new ClassPathXmlApplicationContext("ioc.xml");
			Person bean=(Person)ioc.getBean("person01");  //对应ioc中的id
			System.out.println(bean);
		}
}

在这里插入图片描述

本文链接http://www.taodudu.cc/news/show-1782120.html