Spring---静态与动态工厂之二——改善

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37606901/article/details/82258053

applicationContext.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">

    <!-- 注册动态工厂 -->
    <!-- 在这里调用的是forName.class new insteand....... -->
    <bean id="factory" class="com.myproject.ba3.ServiceFactory"/>

    <!-- 注册Service:动态工厂Bean -->
    <bean id="myService" factory-bean="factory" factory-method="getSomeService"/>
</beans>

MyTest:

package com.myproject.ba3;
/*在本程序中主要用于创建降低工厂与Test之间的耦合度
 * 
**/

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.myproject.ba.ISomeService;
import com.myproject.ba2.ServiceFactory;

public class MyTest {

    @Test
    public void test01(){
        ISomeService service=new ServiceFactory().getSomeService();//动态的工厂-----设置成静态方法以后这样子做调用也可以
        service.doSome();
    }


    @Test
    public void test02() {
        String resource = "com/myproject/ba3/applicationContext.xml";
        ApplicationContext ac=new ClassPathXmlApplicationContext(resource);
        //获取工厂
        ISomeService service=(ISomeService) ac.getBean("myService");
        service.doSome();
    }//出错处:我在执行Mytest的时候,不显示“执行无参数构造器”

    /*在test02()中我的目的就是为了让工厂和和test的耦合度降低下来。----反而使复杂度增加了。-----因为没有使用动态工厂bean----在applicationContext.xml进行设置
     * <bean id="myService" factory-bean="factory" factory-method="getSomeService"/>
     * (2)在Test里面进行设置:
     * 把ServiceFactory factory=(ServiceFactory) ac.getBean("factory");
        ISomeService service=factory.getSomeService();
        改成:ISomeService service=(ISomeService) ac.getBean("myService");

     */

}

猜你喜欢

转载自blog.csdn.net/qq_37606901/article/details/82258053