spring简单范例

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自己做的一个简单例子,希望对入门者有帮助

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值