在本文中,我们将通过一个简单的示例,来演示基于XML配置元数据的Spring IOC 容器。
Spring IOC容器负责实例化,配置和组装Spring Bean。容器通过读取配置元数据来获取要实例化,配置和组装哪些对象的信息。配置元数据以XML,Java注释或Java配置的形式表示。它使您能够表达组成应用程序的对象以及这些对象之间的相互依赖关系。
Spring IoC容器提供了三种方式配置元数据
在此示例中,我们将向Spring IoC容器提供基于XML的配置元数据。
Spring应用程序开发步骤
- 创建Maven项目
- 添加Maven依赖项
- 配置 Spring Beans
- 创建spring容器
- 从Spring容器中获取Bean
1.创建Maven项目
使用您喜欢的IDE创建一个maven项目,本项目使用IDEA开发工具创建。
2.添加Maven依赖项
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
3.配置 Spring Beans
Spring bean是由Spring容器管理的Java对象组成。
package com.spring.ioc.helloworld;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("My Message : " + message);
}
}
配置元数据
<?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-3.0.xsd">
<!--配置HelloWorld bean,交给spirng容器管理-->
<bean id="helloWorld" class="com.spring.ioc.helloworld.HelloWorld">
<property name="message" value="Hello World!" />
</bean>
</beans>
4.创建spring容器
如果应用程序基于XML配置文件加载元数据时,则可以使用ClassPathXmlApplicationContext类加载文件并获取容器对象。
package com.spring.ioc.helloworld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
}
5.从Spring容器中获取Bean
ApplicationContext接口提供getBean()方法从Spring容器中获取bean。
package com.spring.ioc.helloworld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
输出
My Message : Hello World!
想获取源码请私信我获取!
网友评论