基于Spring注解实现的工厂模式
2017-05-14 20:57
330 查看
本文转自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配置的方式实现,今天我们来讲讲如何通过注解的方式实现工厂模式。 主要思路
扫描classPath下的的类,将这些class存储到setmap中
遍历set中的class,找出被自定义facory注解注解过的的class,以beanId,class的对象形式封装到一个map集合里
暴露一个方法getBean,通过beanId查找对于的class的对象,匹配成功后返回该对象
好了,看完代码应该很清楚了,注解是不是给我们带来很多方便了。 留个思考题,如何默认通过类的名字,首个字母小写来作为beanId
好了,看完代码应该很清楚了,注解是不是给我们带来很多方便了。 留个思考题,如何默认通过类的名字,首个字母小写来作为beanId
摘要:
工厂模式是大家熟知的一种设计模式,在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配置的方式实现,今天我们来讲讲如何通过注解的方式实现工厂模式。 主要思路
扫描classPath下的的类,将这些class存储到setmap中
遍历set中的class,找出被自定义facory注解注解过的的class,以beanId,class的对象形式封装到一个map集合里
暴露一个方法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
相关文章推荐
- 基于Spring注解实现工厂模式
- 基于配置文件的工厂设计模式实现,并且做到对象的单例,类似于spring的ioc
- JDBC学习之路(六)--基于Properties配置文件的工厂生产模式的低耦合实现
- 【web开发】基于注解spring的多方法请求的一种controller实现
- Spring整合JDBC模板方法设计模式之基于继承的实现
- 2.1、Spring Web MVC是什么 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职
- Spring基于注解整合Hibernate EhCache实现对象缓存
- 基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)到底有什么区别。
- spring Quartz基于配置文件和注解的实现
- Spring整合JDBC模板方法设计模式之基于组合的实现
- Spring中我们用到的功能实现:基于注解的Ioc自动装配
- spring 基于注解动态切换数据源的实现
- 【第十二章】零配置 之 12.3 注解实现Bean定义、12.4基于Java类定义Bean配置元数据 ——跟我学spring3
- 基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)到底有什么区别。
- 一个简单的基于注解的 Controller (spring 2.5 annotation 方式实现mvc )
- 基于spring3.0注解实现的spring MVC项目
- 基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务(@Trasactional)到底有什么区别。
- 基于JDK动态代理和CGLIB动态代理的实现Spring注解管理事务
- asp.net mvc中自行搭建实现工厂模式的spring.net+三层架构 (15-4-20)
- Spring(四)基于注解配置IOC容器&基于注解实现声明式事务