spring中的控制反转IOC主要是将对象的创建交给spring容器来做,而不需要在程序中主动通过new的方式来造出对象。
spring的配置文件如下:
<?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就当做是java对象 , 由Spring创建和管理。id属性可以当做class这个类的名字,
在程序中通过id属性来获取到对应的类。property属性用来设置这个类的属性的初始值-->
<bean id="h1" class="xyz.bryce.pojo.hello1">
<property name="str" value="hello world"/>
</bean>
</beans>
每当写一个类,就将其写入到上面的spring的配置文件中,就这相当于将这个类交给spring容器进行管理了。
当程序需要用到这个类时,就由spring容器给出这个类的实例。类中的属性 一定要有set
方法,在bean
中,类的属性的赋值是根据set
方法来设置的。如果没有set方法,在 property 标签写上该属性时就会显示错误。
package xyz.bryce.pojo;
public class hello1 {
private String str;
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "hello1{" +
"str='" + str + '\'' +
'}';
}
}
获取类时:
@Test
public void test1(){
ApplicationContext context1 = new ClassPathXmlApplicationContext("beans.xml");
hello1 h1 = (hello1) context1.getBean("h1");
System.out.println(h1);
}
beans.xml
时spring的配置文件,ClassPathXmlApplicationContext
用来从类路径加载配置文件,得到的ApplicationContext
允许spring通过应用程序上下文来创建、获取、管理bean
。通过方法getBean就可以得到对应的类。