3、HelloSpring
beans.xml
<?xm1 version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2081/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https: //www.springframework.org/schema/beans/spring-beans.xsd">
<!--
使用Spring来创建对象,在ESpring这些都称为Bean
类型 变量名= new 类型();
HeLlo heLLo = new HeLLo();
id =变量名
cLass = new 的对象;
property 相当于给对象中的属性设置一个值!
-->
<bean id="hello" class="com.kuang.pojo.Hello">
<!--
Value:具体的值,可以是基本数据类型
ref :引用Spring容器中创建好的对象
-->
<property name="str" value="Spring" / >
</bean>
</beans>
MyTest.java
public class MyTest {
public static void main(string[ ] args) {
//获取Spring的上下文对象!(固定写法,配置xml写法),也可以叫做获取ApplicationContext ;拿到Spring的容器
ApplicationContext context = new ClassPathXm1ApplicationContext("beans.xm1");
//我们的对象现在都在Spring中的管理了,我们要使用,直接去里面取出来就可以!(直接get出来)
He1lo hello = (Hello) context.getBean( "hello");
System.out.println(hello.toString());
}
}
总结:
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的.
反转︰程序本身不创建对象,而变成被动的接收对象.
依赖注入:就是利用set方法来进行注入的.
可以通过newClassPathXmlApplicationContext去浏览一下底层源码.
OK,到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的loC一句话搞定:对象由Spring 来创建,管理,装配!