`

一步步的学习Spring(一)

阅读更多

从demo开始一步步的学习,Spring,来了

 

 

按照Java编码惯例,先编写个接口HelloWorldService

 

 

/**
* @ClassName: HelloWorldService
* @Description: 第一个例子Service接口
* @author sunrain  
* @date 2011-1-1
*/
public interface HelloWorldService {
	public  void  sayHello();
}
 

 

插叙一句,程序中注释很重要,养成良好的编码习惯,Eclipse支持注释的自动生成(设置路径Window->Preference->Java->Code Style->Code Template),导入我的附件1【codetemplates.rar】,然后你就可以在选中类或者方法的时候按住快捷键CTRL+Shift+J来生成自己的代码了;当然了,这只是我自己的注释习惯,你可以改成你的。

 

下面编写实现类HelloWorldServiceImpl

 

 

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* @ClassName: HelloWorldServiceImpl
* @Description: HelloWorldService实现类
* @author sunrain  
* @date 2011-1-1
*/
public class HelloWorldServiceImpl implements HelloWorldService {
	private static final Log log = LogFactory.getLog(HelloWorldServiceImpl.class);
	/**
	* @Fields name : 您的名字
	*/
	private  String  name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	/*
	 * 对您说hello
	* <p>Title: sayHello</p>
	* <p>Description: </p>
	* @see mySpringStudy.HelloWorldService#sayHello()
	*/
	public void sayHello() {
		log.info("hello,"+this.name);
	}

}
 

 

编写Spring bean文件:beans.xml

 

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<bean id="helloWorld" class="HelloWorldServiceImpl">
		<property name="name">
			<value>sunrain</value>
		</property>
	</bean>
</beans>

 

 

编写测试程序:

 

 

 

import junit.framework.TestCase;
import org.springframework.core.io.*;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.xml.XmlBeanFactory;

public class HelloWorldTest extends TestCase {

	public static void main(String[] args) {
		Resource res = new FileSystemResource("beans.xml");
		BeanFactory factory = new XmlBeanFactory(res);
		HelloWorldService hello = (HelloWorldService) factory.getBean("helloWorld");
		hello.sayHello();
	}

}

 

 日志打印:

 

 

0101/19:12:35 <INFO > [org.springframework.core.CollectionFactory 66] JDK 1.4+ collections available
0101/19:12:35 <INFO > [org.springframework.core.CollectionFactory 71] Commons Collections 3.x available
0101/19:12:35 <INFO > [org.springframework.beans.factory.xml.XmlBeanDefinitionReader 163] Loading XML bean definitions from file [G:\workspace\SpringStudy\beans.xml]
0101/19:12:35 <INFO > [HelloWorldServiceImpl 31] hello,sunrain

 

 

至此一个简单的helloWorld编写完毕!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics