IHelloWord.java 这个文件是接口,里面只有一个方法:
/**
*
*/
package src.com.nxh;
/**
* @author nxh
*
*/
public interface IHelloWord {
public String printHelloWord();
}
HelloWord.java 这个文件 实现上面的接口
/**
*
*/
package src.com.nxh;
/**
* @author nxh
*
*/
public class HelloWord implements IHelloWord {
/* (non-Javadoc)
* @see src.com.nxh.IHelloWord#printHelloWord()
*/
public String printHelloWord() {
// TODO Auto-generated method stub
return "helloworld";
}
}
Business.java 一个模拟的业务方法,调用HelloWord
/**
*
*/
package src.com.nxh;
/**
* @author nxh
*
*/
public class Business {
private IHelloWord helloWord;
/**
* @return the hellWord
*/
public IHelloWord getHelloWord() {
return helloWord;
}
/**
* @param hellWord the hellWord to set
*/
public void setHelloWord(IHelloWord hellWord) {
this.helloWord = hellWord;
}
public String getHelloWordString(){
String s=helloWord.printHelloWord();
return s;
}
}
FirstDemo.java 主类
package src.com.nxh;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class FirstDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource rs=new ClassPathResource("beans-config.xml");
BeanFactory factory=new XmlBeanFactory(rs);
Business hello=(Business)factory.getBean("business");
System.out.println(hello.getHelloWordString());
}
}
配置文件 beans-config.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-2.0.xsd">
<bean id="helloword" class="src.com.nxh.HelloWord">
</bean>
<bean id="business" class="src.com.nxh.Business">
<property name="helloWord">
<ref bean="helloword"/>
</property>
</bean>
</beans>
输出结果为:
helloworld
上面 只是我刚学spring自己做的一个简单例子,希望对入门者有帮助