spring helloWord 示例

来源:互联网 发布:淘宝刀具店 编辑:程序博客网 时间:2024/05/16 08:49
 

1.      0828  helloWord 示例

      传统的方法是直接直接调用实体bean 写方法调用bean,现在开始用spring 反射的方式实现方法调用,

首先我们将传统的方法与用spring 的方法实现一个helloword 来对比这两种的区别:

2.      传统的方法:新建一个java工程 ,写helloWord类:

package com.test.bean;
public class helloWord {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public void hello(){
System.out.println("hello:"+name);
}
}

然后写一个main方法调用helloWord对象

public class main {
       public static void main(String[] args) {

// TODO Auto-generated constructor stub
helloWord  helloWord = new helloWord();
helloWord .setName("spring");
helloWord.hello();
}

}

3.   Spring方法

新建一个spring 的配置文件

     1).在文件中配置bean,以及bean属性

      <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- 配置bean -->
   <bean id="helloWord" class="com.test.bean.helloWord">
     <property name="name" value="spring"></property>
   </bean>
</beans>

     2) 1.创建spring的IOC容器
    2.获取示例
    3.调用方法

  package com.test.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class main {
      public static void main(String[] args) {
 // 1.创建spring的IOC容器  
   ApplicationContext ctx =new ClassPathXmlApplicationContext("applicationContext.xml");  
  // 2.获取示例    
   helloWord helloWord =(helloWord)ctx.getBean("helloWord");

         //  3.调用方法
   helloWord.hello();         
       }
}

对比:用反射的方式获取对象调用其方法,bean由spring配置文件进行管理





















0 0