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


开始学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();
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值