spring控制反转(ioc)是为了降低对象之间的耦合性,在没使用ioc之前都是在a对象内部new一个b对象去使用,这样对象之间的耦合性太高,控制反转就是为了降低对象之间的耦合性,所有对象的控制权都交给了第三方容器IOC,由IOC来帮忙创建及注入依赖对象
首先新建一个Student接口及其实现类
//接口
public interface Student {
void get();
}
//实现类
public class StudentImpl implements Student {
private String name;
public void setName(String name) {
this.name = name;
}
public void get() {
System.out.println(this.name);
}
}
然后新建一个bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<beans>
<bean id="stu" class="Test.StudentImpl">
<property name="name" value="小明"/>
</bean>
</beans>
</beans>
这里说下id可以随便取,class为实现类,property是属性
public class Test {
public static void main(String[]args){
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
Student s=context.getBean("stu", Student.class);
s.get();
}
}
最后就会执行get方法打印出小明