Spring第一个案例(10级学员 庞丽课堂总结)

Spring第一个案例(10级学员 庞丽课堂总结)

刚刚接触Spring,我们完成了第一个Spring的案例。下面我就要对Spring第一个案例源代码进行分析。

一、首先我们在Eclipse下新建一个Java项目,在Java项目下引入所需要的Springjar文件,如下图:

二、在项目下的src下新建一个beans.xml文件,文件内的代码如下:

<!—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-2.5.xsd">

  <!-- 配置bean的实例 -->

 <bean id="greetingServiceBean"  class="cn.csdn.hr.service.GreetingServiceBean">

      <!-- propertybean中的属性值 -->

      <property name="greeting">

       <!-属性的值-->

         <value>你好!</value>

      </property>

    </bean>

</beans>


三、在src下创建一个接口GreetingService,在此接口中封装一个方法。

public void sayGeeting();


四、 我们要创建一个实现GreetingService该接口的实体类GreetingServiceBean

1)在此实体类中,首先封装一个属性

代码:

private String greeting;


2)将此属性实现它的set()方法,主要用于bean配置文件中  property属性  name的名称与greeting一致 自动通过set方法注入,依赖注入

代码:

publicvoid setGreeting(String greeting) {

       this.greeting = greeting;

    }


    3)还要实现此实体类的无参构造器,toString()方法用来打印结果的输出。

下面是GreetingService.java类中的完整代码:

publicclass GreetingServiceBean  implements GreetingService{

    // 属性

private String greeting;

    /*bean配置文件中  property属性  name的名称与greeting一致  自动通过set方法注入

     * 依赖注入*/

    publicvoid setGreeting(String greeting) {

       this.greeting = greeting;

    }

    public GreetingServiceBean() {

       super();

       System.out.println("-----------------------------------实例化");

    }

    @Override

    publicvoid sayGeeting() {

       System.out.println(greeting);

    }

}


五、接下来我们要写一个测试类。

import static org.junit.Assert.*;

import org.junit.Test;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.FileSystemResource;

import org.springframework.core.io.Resource; 

import cn.csdn.hr.service.GreetingService;

import cn.csdn.hr.service.GreetingServiceBean;

public class AppMain {

    @Test

    public void test() {

      // 采用三种方式
  /**
   * XmlBeanFactory 
   * ClassPathXmlApplicationContext,
   * XmlWebApplicationContext
   */
  BeanFactory beanFactory = new ClassPathXmlApplicationContext("applicationContext.xml");
  
  // 获取BeanFactory创建的bean对象
  GreetingService greetingService = (GreetingService) beanFactory
    .getBean("greetingServiceBean");// 资源文件中 classbean的id名称
  //GreetingService接口 
  //beanFactory.getBean(""); 实现类的对象 面向接口编程
  
  //使用bean的实例
  greetingService.sayGeeting();}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值