spring编写hello world

来源:互联网 发布:3049域名多少钱 编辑:程序博客网 时间:2024/05/16 15:52
 
Spring目前较为流行的框架之一.核心技术.DI,AOP
虽然不是一个完整的java规范,但在j2ee的开发领域却占着重要的比例.
目前较为流行的SSH体系结构.Struts用于表示层,Spring用于控制层,而hibernate用于数据库的持久层.而Spring在其中却成了其中最较重要的部分.
Spring编写hello world
编写环境eclipse3.2.1,myeclipse 5.1
第一步:创建一个web项目spring1.
第二步:创建一个包,把涉及到的几个类和配置文件放到包中.这里我的包名为test.lyx
第三步:加入spring capabilities..这里我们加入核心包就可以了.还没有用到其它的技术.这时需要产生一个配置文件spring必不可少的.这里我以applicationContext.xml命名.
第四步:创建一个类User.代码如下:
package test.lyx;
publicclass User {
    private String userName;
    public String getUserName() {
        returnuserName;
    }
    publicvoid setUserName(String userName) {
        this.userName = userName;
    }
}
第五步:创建一个类TestUser.代码如下:(用于测试用)
package test.lyx;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestUser {
    public static void main(String[] args) {
         ApplicationContext context=new FileSystemXmlApplicationContext("/src/test/lyx/applicationContext.xml");
        User user=(User)context.getBean("user");
        System.out.print(user.getUserName());
    }
}
第六步:修改applicationContext.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="user" class="test.lyx.User" abstract="false"
       singleton="true" lazy-init="default" autowire="default"
       dependency-check="default">
       <property name="userName">
           <value>hello liuyuanxi</value>
       </property>
    </bean>
</beans>
这一步就是注入的过程.所谓注入就是由容器控制程序之间的关系,在运行的时候给予所有指定的值.
进行TestUser你就会看.hello liuyuanxi.