您的位置:首页 > 编程语言 > Java开发

spring学习笔记1——开始spring之旅

2009-07-04 21:38 417 查看
开始学spring之前编写一个简单的HelloWorld程序,对spring有个感性的理解。

写一个服务类,作用是打出那熟悉的问候,下面显示GreetingService接口,它定义了服务。

public interface GreetingService {
void sayGreeting();
}
GreetingServiceImpl是GreetingService的实现:我们发现此类用两种方式初始化,一个是直接用GreetingServiceImpl(String greeting),另一类是用GreetingServiceImpl()然后调用setGreeting方法来初始化,这两种办法在spring里也可以以配置来实现。

public class GreetingServiceImpl implements GreetingService {
private String greeting;
public GreetingServiceImpl(){}
public GreetingServiceImpl(String greeting){
this.greeting = greeting;
}
public void sayGreeting() {
System.out.println(greeting);
}
public void setGreeting(String greeting){
this.greeting = greeting;
}

}
在spring中配置HelloWorld,相当与:
GreetingServiceImpl greetingService = new GreetingServiceImpl();
greetingService.setGreeting("Buenos Dias!");

<?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="greetingService" class="org.spring.helloworld.GreetingServiceImpl">
<property name="greeting" value="Buenos Dias!" />
</bean>
</beans>
在spring中配置HelloWorld,相当与:

GreetingServiceImpl greetingService = new GreetingServiceImpl("Buenos Dias!");

<bean id="greetingService" class="org.spring.helloworld.GreetingServiceImpl">
<constructor-arg value="Buenos Dias!" />
</bean>
BeanFactory是spring的容器,将把hello.xml文件加载之后main()方法调用BeanFactory的getBean()方法来得到问候服务的引用。

public class HelloApp {
/**
* 通过BeanFactory容器载入xml文件
*/
public void BeanFactoryTest(){
BeanFactory factory = new XmlBeanFactory(new FileSystemResource("xmls/hello.xml"));
GreetingService greetingService = (GreetingService)factory.getBean("greetingService");
greetingService.sayGreeting();
}
/**
* 通过ApplicationContext容器载入xml文件
*/
public void ApplicationContextTest(){
ApplicationContext atx = new ClassPathXmlApplicationContext("org/spring/helloworld/hello.xml");
GreetingService greetingService = (GreetingService)atx.getBean("greetingService");
greetingService.sayGreeting();
}
public static void main(String[] args){
HelloApp ha = new HelloApp();
ha.BeanFactoryTest();
ha.ApplicationContextTest();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: