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

Spring 4.2入门之HelloWorld

2016-01-08 23:11 363 查看
Spring是现代java开发必不可少的一个框架,那么如何使用Spring进行开发呢?那么如何基于Spring进行开发呢?

1.下载Spring

2.下载Common Logging

3.打开eclipse,新建Java工程,此处名为HelloSpring

4.在工程中添加所需jar包,

右键工程,buildPathàconfig buildPath,在弹出的Java Build Path弹出框中选择Libraries中点击Add External JARs,添加外部spring和commonlogging jar包。此处为了方便,添加spring 解压后lib目录下的所有RELEASE.jar 包,另外再添加commonlogging 的jar包。

添加的jar包如图所示。



5.创建源码文件

在src目录下新建com.springtest包,在包中新建 Person.java和MainApp.java文件。

Person类是一个普通的POJO,其源代码为:

package com.springtest;
 
public class Person {
         privateString name;
         privateint age;
        
         publicPerson(){
                   this.name= "zhuwei";
                   this.age= 28;
         }
        
         publicPerson(String name,int age){
                   this.name= name;
                   this.age= age;
         }
         publicString getName() {
                   returnname;
         }
         publicvoid setName(String name) {
                   this.name= name;
         }
         publicint getAge() {
                   returnage;
         }
         publicvoid setAge(int age) {
                   this.age= age;
         }
         publicvoid sayHello(){
                   Stringmessage = "Hello "+this.name+";your age is"+this.age;
                   System.out.println(message);
         }
}




MainAPP类是程序主入口,其源代码为:

package com.springtest;
 
import org.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
 
public class MainApp {
 
         publicstatic void main(String[] args) {
                   //TODO Auto-generated method stub
                   ApplicationContextctx = new ClassPathXmlApplicationContext("bean.xml");
                    
                   Personperson1 = (Person)ctx.getBean("person");
                   person1.sayHello();         
                           
         }
 
}




6.创建J***A Bean配置文件

在src目录下新建bean.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-4.2.xsd">  
         <!--通过属性注入的方式 -->
 <!--  <beanid="person" class="com.springtest.Person">
      <property name="name" value="Leo Chu!"/>
      <property name="age" value="16"/>
  </bean> -->
 
         <!--通过构造器注入 -->
         <beanid="person" class="com.springtest.Person">
      <constructor-arg value="jade yoon"/>
      <constructor-arg value="25"/>
  </bean> 
</beans>


7.执行Java程序,可以看到程序正常运行,并且有输出结果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: