QQ:5654880

用spring框架实现hello,spring的示例

一、用spring框架实现hello,spring的示例

  环境:Myeclipse2015

      

1.写一个实体类

 1 package com.oracle;
 2 /**
 3  * 
 4  * @author Mr
 5  * 一个普通类
 6  */
 7 public class HelloSpring {
 8 
 9     private String myStr;
10 
11     public String getMyStr() {
12         return myStr;
13     }
14     //这个是注入
15     public void setMyStr(String myStr) {
16         this.myStr = myStr;
17     }
18     /**
19      * 输出的方法
20      */
21     public void sayHi(){
22         System.out.println("spring的魔力:"+this.getMyStr());
23     }
24 }

2.编写applicationContext.xml配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans
 3     xmlns="http://www.springframework.org/schema/beans"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xmlns:p="http://www.springframework.org/schema/p"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7      http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
 8     <!-- bean代表的是实体 id就是实例化的“对象” class指定的具体类 -->
 9     <bean id="haha" class="com.oracle.HelloSpring">
10     <!--property  name属性中指定的是实体类中的属性 -->
11         <property name="myStr">
12         <!-- value为属性(实体类中的)赋值 -->
13             <value>音乐家操作框架很牛B</value>
14         </property>
15     </bean>
16 
17 </beans>

3.写测试类测试

 1 package com.test;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 import com.oracle.HelloSpring;
 7 
 8 /**
 9  * 
10  * @author Mr
11  * 测试spring第一个例子
12  */
13 public class Test {
14 
15     public static void main(String[] args) {
16         // 解析applicationContext.xml配置文件
17         ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
18         //去spring配置文件找id属性就是haha
19         HelloSpring hs = (HelloSpring) ac.getBean("haha");
20         //调用方法
21         hs.sayHi();
22     }
23 
24 }

4.运行效果图

 

快乐学编程!!

posted @ 2017-09-15 19:53  大师兄丶2K  阅读(379)  评论(0编辑  收藏  举报