Spring学习之IOC控制反转
(一)IOC:控制反转,简单解释为正常使用对象时我们需要进行对其创建,而现在我们将创建对象的任务交给Spring完成,由IOC容器完成。
(二)代码测试:
先贴上spring一些jar包的功能:
本项目中使用jar包如下:
首先创建一个User类:
package com.entity;
public class User {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "User [userName=" + userName + ", password=" + password + "]";
}
}
在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 name="user" class="com.entity.User">
<property name="userName" value="小可爱"></property>
<property name="password" value="123"></property>
</bean>
</beans>
写测试类:
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.entity.User;
public class TestMethod {
public static void main(String[] args) {
//创建spring容器对象
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取spring创建的user对象
User u=(User)ac.getBean("user");
System.out.println(u);
}
}