下载spring框架
另外,不知道为什么,这里没有commons logging这个jar包,要在下面的链接中下载,是下载···bin.zip文件
打开eclipse,新建一个“java Project” 然后,点击新建的项目,右键-Properties-java Builder Path,在libraries中找到“Add Library”-user library-User libraries,新建一个User Library,名为“spring3.2.2”将lib中的几个jar包都导入进去,在把commons-logging的jar包也一起导进去
当然,也可以把用到的几个jar包导入进去
接下来编写第一个组件(component),他只是一个简单的JavaBean。
package onlyfun.caterpillar;
public class HelloBean {
private String helloWorld;
public void setHelloWorld(String helloWorld){
this.helloWorld = helloWorld;
}
public String getHelloWorld(){
return this.helloWorld;
}
}
接下来,在src目录中新建一个beans-config.xml配置文件,当然,名字可以自己另外命名。
xmlns:xsi=""
xsi:schemaLocation="
/spring-beans-3.2.xsd">
class="onlyfun.caterpillar.HelloBean">
Hello!riseaocean!
最后,编写一个示范程序来运行
package onlyfun.caterpillar;
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 SpringDemo {
@SuppressWarnings({ "deprecation", "resource" })
public static void main(String []args){
Resource rs = new ClassPathResource("beans-config.xml");
BeanFactory factory = new XmlBeanFactory(rs);
HelloBean hello = (HelloBean)factory.getBean("helloBean");
System.out.println(hello.getHelloWorld());
}
}
当然,由于提示The type XmlBeanFactory is deprecated,可以把程序改为:
package onlyfun.caterpillar;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo {
@SuppressWarnings({ "resource" })
public static void main(String []args){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"beans-config.xml"});
BeanFactory factory = context;
HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
}
}
程序运行结果:
Hello!riseaocean!
阅读(2077) | 评论(0) | 转发(0) |