*.hl_mark_KMSmartTagPinkImg{background-color:#ffaaff;}*.hl_mark_KMSmartTagBlueImg{background-color:#99ccff;}*.hl_mark_KMSmartTagYellowImg{background-color:#ffff66;}*.hl_mark_KMSmartTagOrangeImg{background-color:#ffad5b;}*.hl_mark_KMSmartTagGreenImg{background-color:#84e384;}*.hl_mark_KMSmartTagPurpleImg{background-color:#d6acff;}*.hl_mark_KMSmartTagRedImg{background-color:#ff8888;}
.wiz-todo, .wiz-todo-img {width: 16px; height: 16px; cursor: default; padding: 0 10px 0 2px; vertical-align: -7%;-webkit-user-select: none;} .wiz-todo-label { line-height: 2.5;} .wiz-todo-label-checked { color: #666;} .wiz-todo-label-unchecked {text-decoration: initial;} .wiz-todo-completed-info {padding-left: 44px; display: inline-block; } .wiz-todo-avatar { width:20px; height: 20px; vertical-align: -20%; margin-right:10px; border-radius: 2px;} .wiz-todo-account, .wiz-todo-dt { color: #666; }
编写第一个Spring程序
Axe.java
package org.crazyit.app.service;
public class Axe
{
public String chop()
{
return "使用斧头砍柴";
}
}
Person.java
package org.crazyit.app.service;
public class Person
{
private Axe axe;
// 设值注入所需的setter方法
public void setAxe(Axe axe)
{
this.axe = axe;
}
public void useAxe()
{
System.out.println("我打算去砍点柴火!");
// 调用axe的chop()方法,
// 表明Person对象依赖于axe对象
System.out.println(axe.chop());
}
}
BeanTest,java
package lee;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.crazyit.app.service.*;
public class BeanTest
{
public static void main(String[] args)throws Exception
{
// 创建Spring容器
ApplicationContext ctx = new
ClassPathXmlApplicationContext("beans.xml");
// 获取id为person的Bean
Person p = ctx.getBean("person" , Person.class);
// 调用useAxe()方法
p.useAxe();
}
}
说明:
ApplicationContext 的主要实现类是:ClassPathXmlApplicationContext和FileSystemXmlApplicationContext;
前者默认从类路径加载配置文件,后者默认从文件系统加载配置文件。
当含有多个配置文件时,可以通过下面的代码进行加载:
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans1.xml","beans2.xml","beans3.xml"});
beans.xml
<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 配置名为person的Bean,其实现类是org.crazyit.app.service.Person类 -->
<bean id="person" class="org.crazyit.app.service.Person">
<!-- 控制调用setAxe()方法,将容器中axe Bean作为传入参数 -->
<property name="axe" ref="axe"/>
</bean>
<!-- 配置名为axe的Bean,其实现类是org.crazyit.app.service.Axe类 -->
<bean id="axe" class="org.crazyit.app.service.Axe"/>
<!-- 配置名为win的Bean,其实现类是javax.swing.JFrame类 -->
<bean id="win" class="javax.swing.JFrame"/>
<!-- 配置名为date的Bean,其实现类是java.util.Date类 -->
<bean id="date" class="java.util.Date"/>
</beans>
运行:
运行结果: