中文文档
步骤
- 导入maven依赖
- 创建java类
- 配置基于 XML 的元数据配置元数据(不是唯一方法的)
- ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
样例
pojo
public class Hello {
private String string;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
@Override
public String toString() {
return "Hello{" +
"string='" + string + '\'' +
'}';
}
}
beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.spring.pojo.Hello">
<property name="string" value="Hello Spring"/>
</bean>
<!-- collaborators and configuration for this bean go here -->
<!-- more bean definitions go here -->
</beans>
Spring 浅谈IOC(上一篇blog)对应的Spring写法
- beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="carA" class="com.spring.impl.carA"/>
<bean id="carB" class="com.spring.impl.carB"/>
<bean id="carC" class="com.spring.impl.carC"/>
<bean id="service" class="com.spring.service.impl.CarServiceImpl">
<property name="car" ref="carC"/>
</bean>
<!-- collaborators and configuration for this bean go here -->
<!-- more bean definitions go here -->
</beans>
- 实例化spring容器
public class Client {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
CarServiceImpl carService=(CarServiceImpl)context.getBean("service");
carService.getCar();
}
}