基于Spring注解实现的工厂模式

本文转自oschina南寒之星的博文,原文链接如下:https://my.oschina.net/u/923324/blog/832269

摘要: 工厂模式是大家熟知的一种设计模式,在spring BeanFactory将这模式运用自如。 前面讲过如果通过xml配置的方式实现,今天我们来讲讲如何通过注解的方式实现工厂模式。 主要思路 1. 扫描classPath下的的类,将这些class存储到setmap中 2. 遍历set中的class,找出被自定义facory注解注解过的的class,以beanId,class的对象形式封装到一个map集合里 3. 暴露一个方法getBean,通过beanId查找对于的class的对象,匹配成功后返回该对象


[2017-5-16 by Daniel] 今天发现了更简单的方法,请见本人的这篇文章《基于Spring注解实现工厂模式》。


工厂模式是大家熟知的一种设计模式,在spring BeanFactory将这模式运用自如。 前面讲过如果通过xml配置的方式实现,今天我们来讲讲如何通过注解的方式实现工厂模式。 主要思路

  1. 扫描classPath下的的类,将这些class存储到setmap中
  2. 遍历set中的class,找出被自定义facory注解注解过的的class,以beanId,class的对象形式封装到一个map集合里
  3. 暴露一个方法getBean,通过beanId查找对于的class的对象,匹配成功后返回该对象

同样回顾下常见的简单工厂写法

创建一个接口类Pizza


public interface Pizza{
    public float getPrice();
}

MargheritaPizza 类


public class MargheritaPizza implements Pizza{
    public float getPrice() {
        System.out.println("8.5f");
        return 8.5f;

    }
}

CalzonePizza 类


public class CalzonePizza implements Pizza{
    public float getPrice() {
        System.out.println("2.5f");
        return 2.5f;
    }


}

建立工厂类PizzaFactory

通过传入参数id,选择不同的实例类,如果后续不断的增加新类,会频繁的修改create方法,不符合开闭原则


public interface Pizza{
    public float getPrice();
}

MargheritaPizza 类


public class MargheritaPizza implements Pizza{
    public float getPrice() {
        System.out.println("8.5f");
        return 8.5f;

    }
}

CalzonePizza 类


public class CalzonePizza implements Pizza{
    public float getPrice() {
        System.out.println("2.5f");
        return 2.5f;
    }


}

建立工厂类PizzaFactory

通过传入参数id,选择不同的实例类,如果后续不断的增加新类,会频繁的修改create方法,不符合开闭原则


public class PizzaFactory {
    public Pizza create(String id) {
        if (id == null) {
          throw new IllegalArgumentException("id is null!");
        }
        if ("Calzone".equals(id)) {
          return new CalzonePizza();
        }

        if ("Margherita".equals(id)) {
          return new MargheritaPizza();
        }

        throw new IllegalArgumentException("Unknown id = " + id);
      }

}

使用annotation注解方式

注解方式减少对代码的侵入,避免xml配置的繁琐,是spring高版喜欢使用的方式

创建ClassPathSpringScanner 扫描类

获取当前classLoad下的所有class文件


public class ClassPathSpringScanner {


    public static final String CLASS_SUFFIX = ".class";

    private ClassLoader classLoader = getClass().getClassLoader();


    public Set<Class<?>> getClassFile(String packageName) throws IOException {

        Map<String, String> classMap = new HashMap<>(32);
        String path = packageName.replace(".", "/");
        /**
         * 通过classLoader加载文件,循环遍历文件,转换class文件
         */
        Enumeration<URL> urls = classLoader.getResources(path);

        while (urls!=null && urls.hasMoreElements()) {
            URL url = urls.nextElement();
            String protocol = url.getProtocol();
            /**
             * 如果是文件
             */
            if ("file".equals(protocol)) {
                String file = URLDecoder.decode(url.getFile(), "UTF-8");
                File dir = new File(file);
                if(dir.isDirectory()){
                    parseClassFile(dir, classMap);
                }else {
                    throw new IllegalArgumentException("file must be directory");
                }
            } 
        }

        Set<Class<?>> set = new HashSet<>(classMap.size());
        for(String key : classMap.keySet()){
            String className = classMap.get(key);
            try {
                set.add(getClass().forName(className));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return set;
    }

    /**
     * 递归算法把class封装到map集合里
     * @param dir
     * @param packageName
     * @param classMap
     */
    protected void parseClassFile(File dir, Map<String, String> classMap){
        if(dir.isDirectory()){
            File[] files = dir.listFiles();
            for (File file : files) {
                parseClassFile(file, classMap);
            }
        } else if(dir.getName().endsWith(CLASS_SUFFIX)) {
            String name = dir.getPath();
            name = name.substring(name.indexOf("classes")+8).replace("\\", ".");
            addToClassMap(name, classMap);
        }
    }



    private boolean addToClassMap(String name, Map<String, String> classMap){
        if(!classMap.containsKey(name)){
            classMap.put(name, name.substring(0, name.length()-6)); //去掉.class
        }
        return true;
    }

自定义工厂注解@Factory

只要被Factory注解过的类,都能通过beanId实例化对象。

@Target(ElementType.TYPE) 
@Retention(RetentionPolicy.RUNTIME)
public @interface Factory {

    /**
     * 用来表示对象的唯一id
     */
    String id();
}

创建 BeanFactory 接口

public interface BeanFactory {
    public Object getBean(String id);
}

创建BeanFactory 的实现类AnnApplicationContext

将扫描后得到的class封装到一个map里,找出有被Factory注解的类,以beanId,class对象的键值对形式存储。

public class AnnApplicationContext implements BeanFactory{



    private Map<String, Object> factoryClasses = new LinkedHashMap<String, Object>();

    private Set<Class<?>> classSet = new HashSet();


    ClassPathSpringScanner scanner = new ClassPathSpringScanner();
    /*
     * 构造函数初始化扫描获取所有类
     */
    public AnnApplicationContext(String packageName) {

        try {
            //扫描classPath下的所有类,并返回set
            classSet = scanner.getClassFile(packageName);

            /**
             * 遍历所有类,找出有factory注解的类,并封装到linkedHashMap里
             */
            for (Class<?> cls : classSet){
                Factory factory = (Factory) cls.getAnnotation(Factory.class);
                if(factory != null) 
                try {
                    factoryClasses.put(factory.id(), cls.newInstance());
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }  
    }


    /**
     * 输入的id,对应到factoryGroupedClasses的关系,实例化工厂对象
     * @param beanId
     * @return
     */
    @Override
    public Object getBean(String id) {

        return factoryClasses.get(id);
    }

MargheritaPizza 类

添加注释Factory,定义beanId:Margherita

@Factory(id = "margherita")
public class MargheritaPizza implements Pizza{
    public float getPrice() {
        System.out.println("8.5f");
        return 8.5f;

    }
}

CalzonePizza 类

添加注释Factory,定义beanId:Calzone

@Factory(id = "calzone")
public class CalzonePizza implements Pizza{
    public float getPrice() {
        System.out.println("2.5f");
        return 2.5f;
    }


}

测试下

public static void main(String[] args) {
        /**
         * 扫描com.annotation.factory下的类
         */
        AnnApplicationContext factoryProcessor = new AnnApplicationContext("com.annotation.factory.spring");
        Pizza p= (Pizza) factoryProcessor.getBean("Calzone");
        p.getPrice();

    }

好了,看完代码应该很清楚了,注解是不是给我们带来很多方便了。 留个思考题,如何默认通过类的名字,首个字母小写来作为beanId



public interface Pizza{
    public float getPrice();
}

MargheritaPizza 类


public class MargheritaPizza implements Pizza{
    public float getPrice() {
        System.out.println("8.5f");
        return 8.5f;

    }
}

CalzonePizza 类


public class CalzonePizza implements Pizza{
    public float getPrice() {
        System.out.println("2.5f");
        return 2.5f;
    }


}

建立工厂类PizzaFactory

通过传入参数id,选择不同的实例类,如果后续不断的增加新类,会频繁的修改create方法,不符合开闭原则


public class PizzaFactory {
    public Pizza create(String id) {
        if (id == null) {
          throw new IllegalArgumentException("id is null!");
        }
        if ("Calzone".equals(id)) {
          return new CalzonePizza();
        }

        if ("Margherita".equals(id)) {
          return new MargheritaPizza();
        }

        throw new IllegalArgumentException("Unknown id = " + id);
      }

}

使用annotation注解方式

注解方式减少对代码的侵入,避免xml配置的繁琐,是spring高版喜欢使用的方式

创建ClassPathSpringScanner 扫描类

获取当前classLoad下的所有class文件


public class ClassPathSpringScanner {


    public static final String CLASS_SUFFIX = ".class";

    private ClassLoader classLoader = getClass().getClassLoader();


    public Set<Class<?>> getClassFile(String packageName) throws IOException {

        Map<String, String> classMap = new HashMap<>(32);
        String path = packageName.replace(".", "/");
        /**
         * 通过classLoader加载文件,循环遍历文件,转换class文件
         */
        Enumeration<URL> urls = classLoader.getResources(path);

        while (urls!=null && urls.hasMoreElements()) {
            URL url = urls.nextElement();
            String protocol = url.getProtocol();
            /**
             * 如果是文件
             */
            if ("file".equals(protocol)) {
                String file = URLDecoder.decode(url.getFile(), "UTF-8");
                File dir = new File(file);
                if(dir.isDirectory()){
                    parseClassFile(dir, classMap);
                }else {
                    throw new IllegalArgumentException("file must be directory");
                }
            } 
        }

        Set<Class<?>> set = new HashSet<>(classMap.size());
        for(String key : classMap.keySet()){
            String className = classMap.get(key);
            try {
                set.add(getClass().forName(className));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return set;
    }

    /**
     * 递归算法把class封装到map集合里
     * @param dir
     * @param packageName
     * @param classMap
     */
    protected void parseClassFile(File dir, Map<String, String> classMap){
        if(dir.isDirectory()){
            File[] files = dir.listFiles();
            for (File file : files) {
                parseClassFile(file, classMap);
            }
        } else if(dir.getName().endsWith(CLASS_SUFFIX)) {
            String name = dir.getPath();
            name = name.substring(name.indexOf("classes")+8).replace("\\", ".");
            addToClassMap(name, classMap);
        }
    }



    private boolean addToClassMap(String name, Map<String, String> classMap){
        if(!classMap.containsKey(name)){
            classMap.put(name, name.substring(0, name.length()-6)); //去掉.class
        }
        return true;
    }

自定义工厂注解@Factory

只要被Factory注解过的类,都能通过beanId实例化对象。

@Target(ElementType.TYPE) 
@Retention(RetentionPolicy.RUNTIME)
public @interface Factory {

    /**
     * 用来表示对象的唯一id
     */
    String id();
}

创建 BeanFactory 接口

public interface BeanFactory {
    public Object getBean(String id);
}

创建BeanFactory 的实现类AnnApplicationContext

将扫描后得到的class封装到一个map里,找出有被Factory注解的类,以beanId,class对象的键值对形式存储。

public class AnnApplicationContext implements BeanFactory{



    private Map<String, Object> factoryClasses = new LinkedHashMap<String, Object>();

    private Set<Class<?>> classSet = new HashSet();


    ClassPathSpringScanner scanner = new ClassPathSpringScanner();
    /*
     * 构造函数初始化扫描获取所有类
     */
    public AnnApplicationContext(String packageName) {

        try {
            //扫描classPath下的所有类,并返回set
            classSet = scanner.getClassFile(packageName);

            /**
             * 遍历所有类,找出有factory注解的类,并封装到linkedHashMap里
             */
            for (Class<?> cls : classSet){
                Factory factory = (Factory) cls.getAnnotation(Factory.class);
                if(factory != null) 
                try {
                    factoryClasses.put(factory.id(), cls.newInstance());
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }  
    }


    /**
     * 输入的id,对应到factoryGroupedClasses的关系,实例化工厂对象
     * @param beanId
     * @return
     */
    @Override
    public Object getBean(String id) {

        return factoryClasses.get(id);
    }

MargheritaPizza 类

添加注释Factory,定义beanId:Margherita

@Factory(id = "margherita")
public class MargheritaPizza implements Pizza{
    public float getPrice() {
        System.out.println("8.5f");
        return 8.5f;

    }
}

CalzonePizza 类

添加注释Factory,定义beanId:Calzone

@Factory(id = "calzone")
public class CalzonePizza implements Pizza{
    public float getPrice() {
        System.out.println("2.5f");
        return 2.5f;
    }


}

测试下

public static void main(String[] args) {
        /**
         * 扫描com.annotation.factory下的类
         */
        AnnApplicationContext factoryProcessor = new AnnApplicationContext("com.annotation.factory.spring");
        Pizza p= (Pizza) factoryProcessor.getBean("Calzone");
        p.getPrice();

    }

好了,看完代码应该很清楚了,注解是不是给我们带来很多方便了。 留个思考题,如何默认通过类的名字,首个字母小写来作为beanId

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
视频详细讲解,需要的小伙伴自行百度网盘下载,链接见附件,永久有效。 1、课程简介 Spring框架是一系列应用框架的核心,也可以说是整合其他应用框架的基座。同时还是SpringBoot的基础。在当下的市场开发环境中,Spring占据的地位是非常高的,基本已经成为了开发者绕不过去的框架了。它里面包含了SpringSpringMVC,SpringData(事务),SrpingTest等等。 其中: Spring本身里面包含了两大核心IOC和AOP。IOC负责降低我们代码间的依赖关系,使我们的项目灵活度更高,可复用性更强。AOP是让方法间的各个部分更加独立,达到统一调用执行,使后期维护更加的方便。 SpringMVC本身是对Servlet和JSP的API进行了封装,同时在此基础上进一步加强。它推出的一套注解,可以降低开发人员的学习成本,从而更轻松的做表现层开发。同时,在3.x版本之后,它开始之初Rest风格的请求URL,为开发者提供了开发基于Restful访问规则的项目提供了帮助。 SpringData是一组技术合集。里面包含了JDBC,Data JPA,Data Redis,Data Mongodb,Data Rabbit,Data ElasticSearch等等。合集中的每一项都是针对不同数据存储做的简化封装,使我们在操作不同数据库时,以最简洁的代码完成需求功能。 SpringTest它是针对Junit单元测试的整合。让我们在开发中以及开发后期进行测试时,直接使用Junit结合spring一起测试。 本套课程中,我们将全面剖析SpringSpringMVC两个部分。从应用场景分析,到基本用法的入门案例,再到高级特性的分析及使用,最后是执行原理的源码分析。让学生通过学习本套课程不仅可以知其然,还可以知其所以然。最终通过一个综合案例,实现灵活运用Spring框架中的各个部分。 2、适应人群 学习spring,要有一定的Java基础,同时应用过spring基于xml的配置。(或者学习过官网的Spring课程) 学习springmvc,要有一定java web开发基础。同时对spring框架要有一定了解。 3、课程亮点 系统的学习Spring框架中各个部分,掌握Spring中一些高级特性的使用。 l Spring IoC n 设计模式-工厂模式 n 基础应用-入门案例 n 基础应用-常用注解使用场景介绍及入门 n 高级特性-自定义BeanNameGenerator n 高级特性-自定义TypeFilter n 高级特性-ImportSelector和ImportBeanDefinitionRegistrar的分析 n 高级特性-自定义ImportSelector n 高级特性-FilterType中的AspectJTypeFilter的使用 n 高级特性-自定义ImportBeanDefinitionRegistrar n 高级特性-自定义PropertySourceFactory实现解析yaml配置文件 n 源码分析-BeanFactory类视图和常用工厂说明 n 源码分析-AnnotationConfigApplicationContext的register方法 n 源码分析-AnnotationConfigApplicationContext的scan方法 n 源码分析-AbstractApplicationContext的refresh方法 n 源码分析-AbstractBeanFactory的doGetBean方法 l Spring Aop n 设计模式-代理模式 n 编程思想-AOP思想 n 基础应用-入门案例 n 基础应用-常用注解 n 高级应用-DeclareParents注解 n 高级应用-EnableLoadTimeWeaving n 源码分析-@EnableAspectJAutoproxy注解加载过程分析 n 源码分析-AnnotationAwareAspectJAutoProxyCreator n 技术详解-切入点表达式详解 l Spring JDBC n 基础应用-JdbcTemplate的使用 n 源码分析-自定义JdbcTemplate n 设计模式-RowMapper的策略模式 n 高级应用-NamedParameterJdbcTemplate的使用 n 源码分析-TransactionTemplate n 源码分析-DataSourceUtils n 源码分析-TransactionSynchronizationManager

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值