Spring的第一个例子

时间:2023-03-03 22:37:11

Spring 的控制翻转IoC,或者依赖注入。在测试类中没有new一个新对象,对象是从xml文件中注入的。

xml文件中的<beans>是一个大容器,里面的<bean>就是容器里面的内容,这些内容是一个一个的实例对象。

我们把对象创建在了xml文件中,所以就不用再在Java中创建对象了,当我们使用这些对象的时候,就从xml的bean注入即可。

1.创建类

package com.wangcf;

public class HelloWorld {
private String name;
public void sayHello(){
System.out.println("Hello World"+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

2.创建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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
>
<!-- 注册一个Hello World,实例名称为HelloWorld -->
<bean name="helloworld" class="com.wangcf.HelloWorld">
<property name="name">
<value>小明</value>
</property>
</bean>
</beans>

3.创建测试类

package com.wangcf;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloTest { @Test
public void testSayHello() {
//创建Spring 容器
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
//从容器中得到一个bean,也就是一个实例对象
HelloWorld hello=(HelloWorld)context.getBean("helloworld");
hello.sayHello();
} }

4.输出结果

Spring的第一个例子