Spring2.5.5学习1

晕阿,写完的东东保存不了,全没了。只好再写一次了。。。。
Spring入门程序还真是简单阿。比struts2,ejb3简单明了很多。当然前两者也不难。
Spring的核心应该就两个,ioc和aop。先看ioc。

package spring.helloworld;

/**
* Created by IntelliJ IDEA.
* User: Ivan
* Date: 2008-8-27
* Time: 19:43:59
* To change this template use File | Settings | File Templates.
*/
public class People {
private String name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String say(){
return "I'm " + name + " and I'm " + age;
}
}

最简单的java类,没什么可说的。
在classpath根目录上新建个xml文件,随便取个名字,我叫applicationContext.xml.
这是spring注入的配置文件,spring支持多种配置,不过推荐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="People" class="spring.helloworld.People">
<property name="age">
<value>22</value>
</property>
<property name="name">
<value>Ivan</value>
</property>
</bean>
</beans>

在这里,<bean>就是需要注入的类,id为确认bean的唯一性的,不能重复。class不用说了吧。<property>就是需要注入的属性,name是属性的名称,value就是值了贝。应该很直观吧。
接着写个测试类。

package spring.helloworld;

import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import org.junit.Test;
/**
* Created by IntelliJ IDEA.
* User: Ivan
* Date: 2008-8-27
* Time: 19:51:40
* To change this template use File | Settings | File Templates.
*/
public class TestPeople extends AbstractDependencyInjectionSpringContextTests{

private People people;

public void setPeople(People people) {
this.people = people;
}

@Test
public void testSay(){
assertEquals("I'm Ivan and I'm 22",people.say());
}

protected String[] getConfigLocations() {
return new String[]{"classpath:applicationContext.xml"};
}
}

TestPeople继承了AbstractDependencyInjectionSpringContextTests,这是spring里面内置的测试用抽象类,spring内置了完善的测试,不细究。覆盖getConfigLocations这个方法,new String[]{"classpath:applicationContext.xml"};返回一个String数组,里面是配置文件的路径,注意写法。。。。在运行测试的时候,会自动加载配置文件,并给属性注入值,需要做的只是一个set方法,即可。单元测试用的junit4.4,不出意外应该就是绿条了。
spring内置测试还没研究。
对于配置文件,还可以使用注释来代替,作用一模一样,spring手册上就有。
相对而言,这个程序相当于当初入门时的helloworld了。 :D
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值