spring学习笔记1-第一个spring程序

下载spring包

主要用到spring.jar和commons-logging.jar,还有测试包junit.jar

创建接口类

public interface animalBean{
    void dog();
}

创建接口实现

public class DogBean implements AnimalBean{
  public void dog(){
    System.out.println("wang! wang! wang!")    
  }  
}

加入spring配置文件

<?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:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-2.5.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

</beans>      

在配置文件中加入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:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-2.5.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <bean id="AnimalBean" class="xxx.xx.xx.AnimalBean"/>
</beans>      

创建测试类

public class TestClass{
  public void testMethod throws Exception{
    ApplicationContext context = new ClassPathXmlApplicationContext("xxx,xml");
    AnimalBean animal = (AnimalBean )context.getBean("animalBean");
    animal.dog();
  }
}

结果:wang! wang! wang!

 

代码下载:https://files.cnblogs.com/files/hzmaozhetao/spring%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B01-%E7%AC%AC%E4%B8%80%E4%B8%AAspring%E7%A8%8B%E5%BA%8F.zip

posted @ 2017-01-05 17:58  熊猫大侠hz  阅读(124)  评论(0)    收藏  举报