慕课网学习spring入门篇-Spring Bean装配(上)

来源:互联网 发布:淘宝页面生成器 编辑:程序博客网 时间:2024/06/07 05:24

专题二 Bean

  • Bean配置项
  • Bean的作用域
  • Bean的生命周期
  • Bean的自动装配
  • Resources&ResourceLoader

在Spring IOC里面,把一切配置到IOC容器里面的实体或者是对象都称为Bean。

Bean配置项

  • id,在整个IOC容器中的唯一标识
  • Class,具体要实例化的类
  • Scope,范围也就是作用域
  • Constructor arguments,构造器参数,用于构造器注入
  • Properties,属性,用于设值注入
  • Autowiring mode,自动装配模式
  • lazy-initialization mode,懒加载模式
  • Initialization/destruction method,初始化和销毁的方法
  • 等….
    在使用的时候理论上讲只有Class是必须的,其他的都可以不配置,但是如果想从bean容器中得到某一个实例,有两种方式:1、通过id来获取(需要配置id)。2、通过类型来获取(只需配置Class)。

Bean的作用域

  • singleton:单例,指一个Bean容器中只存在一份。
  • prototype:每次请求(每次使用)创建新的实例,destory方式不生效
  • request:每次http请求创建一个实例且仅在当前request内有效
  • session:同上,每次http请求创建,当前session内有效
  • global session:基于portlet的web中有效(portlet定义了global session),如果是在web中,同session。portlet是一种web组件,和servlet类似,做应用的集成,OA系统、HR系统、财务系统等,在企业内部通常不会每个系统登录,会做一个portal,会把每个系统常用的功能列在其中,这个portal会和所有的系统做单点登录,登录portal之后,可以点击其中任意一个区域或链接,跳到相应的系统中去,跳过去之后这已经是两个系统,两个web应用了,所以是两个session,那global session 就是指在这种情况下,session的作用范围。

例子

单例模式,一个Bean容器中只存在一份。通过hashcode()来区分是否是同一个bean。

package com.imooc.bean;public class BeanScope {    public void say() {        System.out.println("BeanScope say : " + this.hashCode());    }}
//spring-beanscope.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" >        <bean id="beanScope" class="com.imooc.bean.BeanScope" scope="singleton"></bean> </beans>
package com.imooc.test.bean;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.BlockJUnit4ClassRunner;import com.imooc.bean.BeanScope;import com.imooc.test.base.UnitTestBase;@RunWith(BlockJUnit4ClassRunner.class)public class TestBeanScope extends UnitTestBase {    public TestBeanScope() {        super("classpath*:spring-beanscope.xml");    }    @Test    public void testSay() {        BeanScope beanScope = super.getBean("beanScope");        beanScope.say();        BeanScope beanScope2 = super.getBean("beanScope");        beanScope2.say();    }    @Test    public void testSay2() {        BeanScope beanScope  = super.getBean("beanScope");        beanScope.say();    }}

执行testSay()方法,发现输出的两次结果是相同的,是因为在测试方法testSay()执行前会调用一次父类的@Before的方法,然后执行testSay()方法,之后执行@After方法。在@Before的before()方法中,会创建一个ClassPathXmlApplicationContext上下文,就是只创建了一个bean。所以testSay()方法中两次执行结果相同。而testSay2()方法又另外执行了before()方法,是从两个Spring Ioc容器获取的。因而会有另一个上下文,是两个bean,会有不同的hashcode。

prototype:每次请求(每次使用)创建新的实例,destory方式不生效

<?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="beanScope" class="com.imooc.bean.BeanScope" scope="prototype"></bean> </beans>

其他代码同单例模式,发现testSay()方法中两次输出结果不同,就是说在同一个容器里,针对每次请求创建新的实例。

Bean的生命周期

  • 定义,在XML文件中配置的bean
  • 初始化,当IOC容器,也就是context.start()启动的时候去加载XML文件里面的bean并初始化生成bean的实例
  • 使用,实际开发中,从bean容器中取出一个bean的实例,然后去调用方法
  • 销毁,在bean容器停止的时候,去销毁由当前bean容器创建的所有bean的实例

初始化

  • 实现org.springframework.bean.factory.InitializingBean接口,覆盖afterPropertiesSet方法
  • 配置init-method,在XML配置文件的bean配置中加入init-method属性,属性名中的方法名要对应class中的类的方法
    - bean id=”exampleInitBean” class=”examples.ExampleBean” init-method=”init”
    - public class ExampleBean{ public void init() {}}

销毁

  • 实现org.springframework.bean.factory.DisposableBean接口,覆盖destory方法
  • 配置destory-method,在XML配置文件的bean配置中加入destory-method属性,属性名中的方法名要对应class中的类的方法
    - bean id=”exampleInitBean” class=”examples.ExampleBean” destory-method=”cleanup”
    - public class ExampleBean{ public void cleanup() {}}
  • 配置全局默认初始化、销毁方法。在IOC容器加载和销毁的时候分别调用init方法和destory方法
<?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"        default-init-method="init" default-destroy-method="destory"> </beans>

例子1,配置init-method和destory-method

spring-lifecycle.xml,添加了初始化方法”start”和销毁方法”stop”

<?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="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle"  init-method="start" destroy-method="stop"></bean> </beans>

在BeanLifeCycle类中添加上面两个方法

package com.imooc.lifecycle;import org.springframework.beans.factory.DisposableBean;import org.springframework.beans.factory.InitializingBean;public class BeanLifeCycle {    public void start() {        System.out.println("Bean start .");    }    public void stop() {        System.out.println("Bean stop.");    }}

测试案例,在extends UnitTestBase父类中的@Before和@After方法中有启动容器和销毁容器的方法

package com.imooc.test.lifecycle;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.BlockJUnit4ClassRunner;import com.imooc.test.base.UnitTestBase;@RunWith(BlockJUnit4ClassRunner.class)public class TestBeanLifecycle extends UnitTestBase {    public TestBeanLifecycle() {        super("classpath:spring-lifecycle.xml");    }    @Test    public void test1() {        super.getBean("beanLifeCycle");    }}

例子2,实现InitializingBean和DisposableBean接口

spring-lifecycle.xml,不需要init-method和destroy-method属性

<?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">        <!-- init-method="start" destroy-method="stop" -->        <bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle"></bean> </beans>

BeanLifeCycle.java,实现InitializingBean, DisposableBean接口

package com.imooc.lifecycle;import org.springframework.beans.factory.DisposableBean;import org.springframework.beans.factory.InitializingBean;public class BeanLifeCycle implements InitializingBean, DisposableBean {    @Override    public void destroy() throws Exception {        System.out.println("Bean destroy.");    }    @Override    public void afterPropertiesSet() throws Exception {        System.out.println("Bean afterPropertiesSet.");    }}

测试案例不变。

例子3,使用全局默认的初始化和销毁方法

spring-lifecycle.xml,default-init-method和default-destroy-method

<?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"         default-init-method="defautInit" default-destroy-method="defaultDestroy">        <!-- init-method="start" destroy-method="stop" -->        <bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle" ></bean> </beans>

BeanLifeCycle.java

package com.imooc.lifecycle;import org.springframework.beans.factory.DisposableBean;import org.springframework.beans.factory.InitializingBean;public class BeanLifeCycle {    public void defautInit() {        System.out.println("Bean defautInit.");    }    public void defaultDestroy() {        System.out.println("Bean defaultDestroy.");    }}

测试案例不变。

当同时使用三种方式

package com.imooc.lifecycle;import org.springframework.beans.factory.DisposableBean;import org.springframework.beans.factory.InitializingBean;public class BeanLifeCycle implements InitializingBean, DisposableBean {    public void defautInit() {        System.out.println("Bean defautInit.");    }    public void defaultDestroy() {        System.out.println("Bean defaultDestroy.");    }    @Override    public void destroy() throws Exception {        System.out.println("Bean destroy.");    }    @Override    public void afterPropertiesSet() throws Exception {        System.out.println("Bean afterPropertiesSet.");    }    public void start() {        System.out.println("Bean start .");    }    public void stop() {        System.out.println("Bean stop.");    }}<?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"         default-init-method="defautInit" default-destroy-method="defaultDestroy">        <bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle" init-method="start" destroy-method="stop"></bean> </beans>package com.imooc.test.lifecycle;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.BlockJUnit4ClassRunner;import com.imooc.test.base.UnitTestBase;@RunWith(BlockJUnit4ClassRunner.class)public class TestBeanLifecycle extends UnitTestBase {    public TestBeanLifecycle() {        super("classpath:spring-lifecycle.xml");    }    @Test    public void test1() {        super.getBean("beanLifeCycle");    }}

执行结果:
Bean afterPropertiesSet.
Bean start .
Bean destroy.
Bean stop.
先执行的是实现InitializingBean接口的方法,然后执行的是配置init-method参数的方法,全局默认的default-init-method的方法没有执行。销毁顺序与初始化顺序相同。
当一个bean配置了init-method、destroy-method或者实现了InitializingBean、DisposableBean接口,默认的初始化和销毁方法就会不生效。另外,当配置了全局默认的初始化和销毁方法,在bean中没有这两个方法时,程序不会出现异常。

Aware

  • Spring提供了一些以Aware结尾的接口,实现了Aware接口的bean在被初始化之后,可以获取相应资源
  • 通过Aware接口,可以对Spring相应资源进行操作(一定要慎重)
  • 为对Spring进行简单的扩展提供了方便的入口

  • ApplicationContextAware:ApplicationContextAware会向实现了这个接口的bean提供ApplicationContext也就是IOC容器的上下文信息。实现了这个接口的bean必须配置到spring的配置文件中去,并且由spring的bean容器去加载。

  • BeanNameAware:会提供BeanName定义的内容。
Name Injected(注入) Dependency ApplicationContextAware declaring ApplicationContext(声明应用上下文) ApplicationEventPublisherAware Event publisher of the enclosing ApplicationContext(事件发布) BeanClassLoaderAware Class loader used to load the bean classes(用于加载bean的类加载器) BeanFactoryAware Declaring BeanFactory(声明bean工程) BeanNameAware Name of the declaring bean(声明bean名称) BootstrapContextAware Resource adapter BootstrapContext the container runs in.Typically available only in JCA aware ApplicationContexts MessageSourceAware Configured strategy for resolving messages NotificationPublisherAware Spring JMX notification(通知) publisher PortletConfigAware Current PortletConfig the container runs in.Valid only in a web-aware PortletContextAware Current PortletConfig the container runs in.Valid only in a web-aware ResourceLoaderAware Configured loader for low-level access to resources ServletConfigAware Current ServletConfig the container runs in ServletContextAware Current ServletContext the container runs in

例子,实现ApplicationContextAware

MoocApplicationContext,实现了ApplicationContextAware方法

package com.imooc.aware;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;public class MoocApplicationContext implements ApplicationContextAware  {    @Override    public void setApplicationContext(ApplicationContext applicationContext)            throws BeansException {        System.out.println("MoocApplicationContext : " + applicationContext.getBean("moocApplicationContext").hashCode());    }}

spring-aware.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" >    <bean id="moocApplicationContext" class="com.imooc.aware.MoocApplicationContext" ></bean> </beans>

TestAware.java

package com.imooc.test.aware;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.BlockJUnit4ClassRunner;import com.imooc.test.base.UnitTestBase;@RunWith(BlockJUnit4ClassRunner.class)public class TestAware extends UnitTestBase {    public TestAware() {        super("classpath:spring-aware.xml");    }    @Test    public void testMoocApplicationContext() {        System.out.println("testMoocApplicationContext : " + super.getBean("moocApplicationContext").hashCode());    }}

执行结果:
MoocApplicationContext : 3213500
testMoocApplicationContext : 3213500

在初始化容器时,调用setApplicationContext方法,得到了当前的bean。并且在bean中获取的实例与在单元测试方法中从IOC容器中得到的实例是同一个。也就是说,成功的把当前的applicationContext注入到了方法中,可以在类中使用。
在实际的使用中可以这样声明:

public class MoocApplicationContext implements ApplicationContextAware  {    private ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext applicationContext)            throws BeansException {        this.applicationContext = applicationContext;        System.out.println("MoocApplicationContext : " + applicationContext.getBean("moocApplicationContext").hashCode());    }    //这样在其他的方法中就可以使用applicationcontext,来进行相应的操作,如判断bean是否存在    public void a() {        this.applicationContext.containsBean("MoocApplicationContext");    }}

例子,实现BeanNameAware

package com.imooc.aware;import org.springframework.beans.factory.BeanNameAware;public class MoocBeanName implements BeanNameAware {    private String beanName;    @Override    public void setBeanName(String name) {        this.beanName = name;        System.out.println("MoocBeanName : " + name);    }}<?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="moocApplicationContext" class="com.imooc.aware.MoocApplicationContext" ></bean> -->    <bean id="moocBeanName" class="com.imooc.aware.MoocBeanName" ></bean> </beans>package com.imooc.test.aware;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.BlockJUnit4ClassRunner;import com.imooc.test.base.UnitTestBase;@RunWith(BlockJUnit4ClassRunner.class)public class TestAware extends UnitTestBase {    public TestAware() {        super("classpath:spring-aware.xml");    }    @Test    public void textMoocBeanName() {        System.out.println("textMoocBeanName : " + super.getBean("moocBeanName").hashCode());    }}执行结果:MoocBeanName : moocBeanNametextMoocBeanName : 553871028

同时实现ApplicationContextAware和BeanNameAware

setBeanName()方法得到beanname,并赋值给成员变量beanName。在setApplicationContext()方法中,通过容器的getBean方法,得到由setBeanName传入的bean的实例

public class MoocBeanName implements BeanNameAware, ApplicationContextAware {    private String beanName;    @Override    public void setBeanName(String name) {        this.beanName = name;        System.out.println("MoocBeanName : " + name);    }    @Override    public void setApplicationContext(ApplicationContext applicationContext)            throws BeansException {        System.out.println("setApplicationContext : " + applicationContext.getBean(this.beanName).hashCode());    }}单元测试同BeanNameAware例子。输出结果:MoocBeanName : moocBeanNamesetApplicationContext : 3213500textMoocBeanName : 3213500

可以看到输出结果中两个hashcode是相同的,也就是说,无论是通过aware接口传入还是通过启动容器的getBean得到的bean,是同一个。

Bean的自动装配(Autowiring)

之前,我们知道了依赖注入的两种方式,设值注入和构造器注入,都需要在bean的xml文件中配置显示的声明,在bean的内部声明property或constructor-arg。下面来介绍bean的自动装配。
自动装配的类型:
- No:不做任何操作
- byname:根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配。如果bean的id重复,IOC容器启动就会失败,会提示不能存在两个相同的id
- byType:如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配;如果存在多个该类型bean,那么抛出异常,并指出不能使用byType方式进行自动装配;如果没有找到相匹配的bean,则什么事都不发生
- Constructor:与byType方式类似,不同之处在于它应用构造器参数。如果容器中没有找到与构造器参数类型一致的bean,那么抛出异常

例子,byName

package com.imooc.autowiring;public class AutoWiringDAO {    public void say(String word) {        System.out.println("AutoWiringDAO : " + word);    }}
package com.imooc.autowiring;public class AutoWiringService {    private AutoWiringDAO autoWiringDAO;    public void setAutoWiringDAO(AutoWiringDAO autoWiringDAO) {        System.out.println("setAutoWiringDAO");        this.autoWiringDAO = autoWiringDAO;    }    public void say(String word) {        this.autoWiringDAO.say(word);    }}

如果按照之前的配置方式会在xml中id=autoWiringService的bean中配置property name ref。当做了根据name自动装配后不需要这样了。只需要配置两个bean,在引用的bean中,声明set方法

<?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"         default-autowire="byName">        <bean id="autoWiringService" class="com.imooc.autowiring.AutoWiringService" ></bean>        <bean id="autoWiringDAO" class="com.imooc.autowiring.AutoWiringDAO" ></bean> </beans>

单元测试

package com.imooc.test.autowiring;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.BlockJUnit4ClassRunner;import com.imooc.autowiring.AutoWiringService;import com.imooc.test.base.UnitTestBase;@RunWith(BlockJUnit4ClassRunner.class)public class TestAutoWiring extends UnitTestBase {    public TestAutoWiring() {        super("classpath:spring-autowiring.xml");    }    @Test    public void testSay() {        AutoWiringService service = super.getBean("autoWiringService");        service.say(" this is a test");    }}

执行结果:
setAutoWiringDAO
AutoWiringDAO : this is a test
AutoWiringService中,setAutoWiringDAO被执行,是因为设置了default-autoware=”byName”,然后会在Spring的IOC容器中寻找名称为autoWiringDAO完全一致的id,然后赋值给AutoWiringService中的属性autoWiringDAO。

用自动装配的方式,能够减少在bean的配置文件中的配置的代码的行数,也能够使bean看起来更简洁一些

例子,byType

只需在xml文件中把default-aware设置为”byType”,其余代码相同

<?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"         default-autowire="byType">        <bean id="autoWiringService" class="com.imooc.autowiring.AutoWiringService" ></bean>        <bean id="autoWiringDAO" class="com.imooc.autowiring.AutoWiringDAO" ></bean> </beans>

需要注意:byType的自动注入与bean的id没有直接关系。

例子,constructor

service类中添加构造方法

package com.imooc.autowiring;public class AutoWiringService {    private AutoWiringDAO autoWiringDAO;    public AutoWiringService(AutoWiringDAO autoWiringDAO) {        System.out.println("AutoWiringService");        this.autoWiringDAO = autoWiringDAO;    }    public void setAutoWiringDAO(AutoWiringDAO autoWiringDAO) {        System.out.println("setAutoWiringDAO");        this.autoWiringDAO = autoWiringDAO;    }    public void say(String word) {        this.autoWiringDAO.say(word);    }}

在xml文件中把default-aware设置为”constructor”,其余代码相同

<?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"         default-autowire="constructor">        <bean id="autoWiringService" class="com.imooc.autowiring.AutoWiringService" ></bean>        <bean class="com.imooc.autowiring.AutoWiringDAO" ></bean> </beans>

容器中需要找到与构造器参数类型一致的bean,是根据类型进行判断的。所以,AutoWiringDAO这个bean没有id也是可以的。

Resources

Resources是针对于资源文件的统一接口
有以下几类:
- UrlResource:URL对应的资源,根据一个URL地址即可构建
- ClassPathResource:获取类路径下的资源文件
- FileSystemResource:获取文件系统里面的资源
- ServletContextResource:ServletContext封装的资源,用于访问ServletContext环境下的资源
- InputStreamResource:针对于输入流封装的资源
- ByteArrayResource:针对于字节数组封装的资源

ResourceLoader,对Resource进行加载的类。在Spring的IOC容器中所有的application context都实现了ResourceLoader这个接口,所有的applicationContext都可以获取Resource的实例

ResourceLoader接口的声明

public interface ResourceLoader {    Resource getResource(String loaction);}

四种前缀类型:
- none:Resource template = ctx.getResource(“some/resource/path/myTemplate.txt”);
- classpath:Resource template = ctx.getResource(“classpath:some/resource/path/myTemplate.txt”);
- file:Resource template = ctx.getResource(“file:/some/resource/path/myTemplate.txt”);
- http:Resource template = ctx.getResource(“http://myserver/logo.png“);

例子

在所有的applicationContext都实现了ResourceLoader接口,那么只需在我们的类中得到applicationContext,即实现接口ApplicationContextAware

package com.imooc.resource;import java.io.IOException;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.core.io.Resource;public class MoocResource implements ApplicationContextAware  {    private ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext applicationContext)            throws BeansException {        //为当前类中的成员变量赋值        this.applicationContext = applicationContext;    }    public void resource() throws IOException {        Resource resource = applicationContext.getResource("classpath:config.txt");//前缀为相对路径方式        System.out.println(resource.getFilename());        System.out.println(resource.contentLength());    }}

http方式:Resource resource = applicationContext.getResource(“http://webmagic.io/docs/zh/posts/ch1-overview/thinking.html“);

file方式:Resource resource = applicationContext.getResource(“file:\C:\Users\Administrator\Workspaces\MyEclipse 2016\Spring\src\main\resources\config.txt”);

none:Resource resource = applicationContext.getResource(“config.txt”);当没有前缀的时候是依赖applicationContext的,我们的applicationContext是在UnitTestBase.java中根据classpath创建的。所以当前这个例子如果没有前缀也是由classpath方式加载的。
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" >        <bean  id="moocResource" class="com.imooc.resource.MoocResource" ></bean> </beans>

单元测试

package com.imooc.test.resource;import java.io.IOException;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.BlockJUnit4ClassRunner;import com.imooc.resource.MoocResource;import com.imooc.test.base.UnitTestBase;@RunWith(BlockJUnit4ClassRunner.class)public class TestResource extends UnitTestBase {    public TestResource() {        super("classpath:spring-resource.xml");    }    @Test    public void testResource() {        MoocResource resource = super.getBean("moocResource");        try {            resource.resource();        } catch (IOException e) {            e.printStackTrace();        }    }}
原创粉丝点击