使用xml方式实现的Spring IOC的简单示例
时间: 2023-12-03 18:46:03 浏览: 100
以下是一个使用 XML 实现 Spring IOC 的简单示例:
1. 编写 Bean 类
```
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("Your Message : " + message);
}
}
```
2. 编写 Spring 配置文件 applicationContext.xml
```
<beans>
<bean id="helloWorld" class="com.example.HelloWorld">
<property name="message" value="Hello World!" />
</bean>
</beans>
```
3. 编写测试类
```
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
```
4. 运行测试类,输出结果为:
```
Your Message : Hello World!
```
以上就是一个使用 XML 实现 Spring IOC 的简单示例。需要注意的是,在 applicationContext.xml 中,我们需要配置 Bean 的信息,包括 id、class 和 property 等。在测试类中,我们通过 ApplicationContext 获取 Bean 的实例,然后调用其方法。
阅读全文
相关推荐















