package com.snowalker.spring01;
public class Axe {
public String chop() {
return "使用斧头砍柴";
}
}
package com.snowalker.spring01;
public class Person {
private Axe axe;
//设值注入所需setter
public void setAxe(Axe axe) {
this.axe = axe;
}
/**
* Person依赖Axe
*/
public void useAxe() {
System.out.println("我打算去砍柴点火");
System.out.println(axe.chop());
}
}
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.snowalker.spring01.Person;
public class BeanTest {
public static void main(String[] args) {
//创建Spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//获取id为person的Bean
Person person = context.getBean("person", Person.class);
//调用useaxe方法
person.useAxe();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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">
<bean id="person" class="com.snowalker.spring01.Person">
<property name="axe" ref="axe"/>
</bean>
<bean id="axe" class="com.snowalker.spring01.Axe"/>
<bean id="win" class="javax.swing.JFrame"/>
<bean id="date" class="java.util.Date"/>
</beans>
<bean../>:元素默认以反射方式调用该类的无参构造器
<property../>:子元素驱动Spring执行setter方法
二月 16, 2016 11:09:04 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@377dca04: startup date [Tue Feb 16 23:09:04 CST 2016]; root of context hierarchy
二月 16, 2016 11:09:04 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
我打算去砍柴点火
使用斧头砍柴
这次介绍了使用Spring开发一个小应用的基本过程;
Spring加载类主要是通过反射特性的,因此反射特性仍有必要进行深入的掌握。