Spring基础:快速入门spring(2):理解Ioc

这里写图片描述

本文将使用简单的例子来说明spring的Ioc是如何实施的。

传统方式

首先我们要看一下不使用Ioc的时候得一个简单的例子。创建一个Teacher的类,此类有一个sayhello的函数,
在另外一个类里面创建实例并调用它。

创建Package

在src目录上右击,创建Java package(com.liumiao.demo.spring)

创建一个名为Teacher的Class

package com.liumiao.demo.spring;

public class Teacher {

    public String sayhello(){
        return "Hello, I am a teacher";
    }
}

创建用于演示的TestDemo的Class

package com.liumiao.demo.spring;

public class TestDemo {

  public static void main(String[] args){
    Teacher person = new Teacher();

    System.out.println(person.sayhello());
  }
}

执行TestDemo

结果如下

Hello, I am a teacher

传统方式的改进

一般的code使用最佳实践对代码进行优化,可能改成下面的样子

引入Person这个Interface

package com.liumiao.demo.spring;

public interface Person {
  public String sayhello();
}

改写Teacher类

package com.liumiao.demo.spring;

public class Teacher implements Person {
  @Override
  public String sayhello(){
    return "Hello, I am a teacher";
  }
}

修改TestDemo

package com.liumiao.demo.spring;

public class TestDemo {

  public static void main(String[] args){
    Person person = new Teacher();

    System.out.println(person.sayhello());
  }
}

执行TestDemo

结果如下

Hello, I am a teacher

结果没有变化。为什么要这样作呢,看起来只是绕圈实现而已,多做无用功的感觉。但其实把这个放大或者放到特定的上下文之中,其作用立即就会显现。举个简单的例子,我们想增加更多的子类的实现,比如实现一个Student的类,扩展或者替换,和其他设计模式进行结合都会非常方便,接下来来看看增加一个Student的实现需要做哪些事情。

增加一个Student的类

package com.liumiao.demo.spring;

public class Student implements Person {
  @Override
  public String sayhello(){
    return "Hello, I am a student.";
  }
}

修改TestDemo

package com.liumiao.demo.spring;

public class TestDemo {

  public static void main(String[] args){
    Person person = new Student();

    System.out.println(person.sayhello());
  }
}

执行TestDemo

结果如下

Hello, I am a student.

修改很少,OCP原则,开闭方便。source过于简单不便多说,可自行在项目中体会。虽然依然很简单有效,但是如果改变的话依然需要修改source,毕竟这里new Student这个操作被hardcoding了,接下来我们在这个基础之上来看看spring是如何做的。

Spring方式

创建spring的配置文件

我们在com.liumiao.demo.spring下面创建一个spring的配置文件spring-cfg.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.xsd">

</beans>

配置spring bean

接下来需要把一些bean设定到spring的配置文件中,我们先把Teacher这个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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="thePerson" class="com.liumiao.demo.spring.Teacher">
  </bean>

</beans>

使用

配置好了之后,spring中使用方式一般按照如下四步

步骤 内容 参考
Step 1 装载spring配置文件 ClassPathXmlApplicationContext
Step 2 从返回的context中检索相应的spring bean context.getBean
Step 3 执行spring bean
Step 4 关闭context context.close

改写TestDemo类

package com.liumiao.demo.spring;

import com.liumiao.demo.spring.Person;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemo {
    public TestDemo() {
    }

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:com/liumiao/demo/spring/spring-cfg.xml");
        Person person = (Person)context.getBean("thePerson", Person.class);
        System.out.println(person.sayhello());
        context.close();
    }
}

执行结果

Nov 24, 2016 8:41:31 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
情報: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@722c41f4: startup date [Fri Nov 24 20:41:30 CST 2016]; root of context hierarchy
Nov 24, 2016 8:41:31 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
情報: Loading XML bean definitions from class path resource [com/liumiao/demo/spring/spring-cfg.xml]
Hello, I am a teacher
Nov 24, 2016 8:41:31 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
情報: Closing org.springframework.context.support.ClassPathXmlApplicationContext@722c41f4: startup date [Fri Nov 24 20:41:30 CST 2016]; root of context hierarchy

使用Student类

从使用Teacher类变成使用Student类,在改善过了的传统方式需要修改少量代码,而使用Spring的话,则只需要向如下这样修改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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="thePerson" class="com.liumiao.demo.spring.Student">
  </bean>

</beans>

执行结果

Nov 24, 2016 8:44:53 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
情報: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@722c41f4: startup date [Fri Nov 24 20:44:53 CST 2016]; root of context hierarchy
Nov 24, 2016 8:44:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
情報: Loading XML bean definitions from class path resource [com/liumiao/demo/spring/spring-cfg.xml]
Nov 24, 2016 8:44:54 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
情報: Closing org.springframework.context.support.ClassPathXmlApplicationContext@722c41f4: startup date [Fri Nov 24 20:44:53 CST 2016]; root of context hierarchy
Hello, I am a student.

这样就可以看到spring使用这种方式非常简单的通过修改设定文件来实现所需的功能的过程

备注:过程中如需用到commons-logging,下载地址为https://commons.apache.org/proper/commons-logging/download_logging.cgi
展开阅读全文

spring 加载applicationContext.xml文件报错

07-11
主程序: ![图片说明](https://img-ask.csdn.net/upload/201607/11/1468227442_924549.png) 目录结构: ![图片说明](https://img-ask.csdn.net/upload/201607/11/1468227465_28252.png) applicationContext.xml: ![图片说明](https://img-ask.csdn.net/upload/201607/11/1468227487_415892.png) jar包: ![图片说明](https://img-ask.csdn.net/upload/201607/11/1468227505_842386.png) 报错: 七月 11, 2016 4:50:21 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4d405ef7: startup date [Mon Jul 11 16:50:21 CST 2016]; root of context hierarchy 七月 11, 2016 4:50:21 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [applicationContext.xml] Exception in thread "main" java.lang.IllegalArgumentException at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80) at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101) at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300) at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230) at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153) at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130) at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285) at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at main.Test.main(Test.java:12)

关于spring配置的错误

04-08
以下是错误信息 2015-4-8 8:40:40 org.springframework.context.support.AbstractApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@a01335: startup date [Wed Apr 08 08:40:40 CST 2015]; root of context hierarchy 2015-4-8 8:40:40 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [beans.xml] Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/aop] Offending resource: class path resource [beans.xml] at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:318) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1435) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1428) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:195) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:139) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:108) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243) at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127) at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at com.spring.userService.UserServiceTest.main(UserServiceTest.java:16) 这是我的jar包 #![图片说明](https://img-ask.csdn.net/upload/201504/08/1428453489_728991.png)求大神帮忙看看啊
©️2020 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值