(一)IOC:控制反转,简单解释为正常使用对象时我们需要进行对其创建,而现在我们将创建对象的任务交给Spring完成,由IOC容器完成。
(二)代码测试:
先贴上spring一些jar包的功能:
本项目中使用jar包如下:
首先创建一个User类:
package com.entity;
public class People {
private String name;
private int age;
public People() {
super();
// TODO Auto-generated constructor stub
}
public People(String name, int age) {
super();
this.name = name;
this.age = 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 "People [name=" + name + ", age=" + age + "]";
}
}
在src目录下写一个applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<!-- 将user对象交给spring进行创建 -->
<!--
name:调用时用的名字
class:路径
-->
<bean id="people1" class="com.entity.People">
<property name="name" value="小可爱"></property>
<property name="age" value="123"></property>
</bean>
<bean id="people2" class="com.entity.People">
<constructor-arg type="int" value="2"></constructor-arg>
<constructor-arg type="String" value="小帅气"></constructor-arg>
</bean>
<bean id="people3" class="com.entity.People">
<constructor-arg index="0" value="小奇怪"></constructor-arg>
<constructor-arg index="1" value="56"></constructor-arg>
</bean>
</beans>
写测试类:
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.entity.People;
public class TestMethod {
public static void main(String[] args) {
//创建spring容器对象
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取spring创建的user对象
People p1=(People)ac.getBean("people1");
People p2=(People)ac.getBean("people2");
People p3=(People)ac.getBean("people3");
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
}
}