好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

使用BeanFactory实现创建对象

本文实例为大家分享了beanfactory实现 创建对象 的具体代码,供大家参考,具体内容如下

说明:

 其作用是减少层与层之间的依赖。

实现步骤:

编写2个类(student,teacher)再编写beans.properties文件,接着编写beanfactory类,最后编写测试类beantest。

参考代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

/**

  *beans.properties文件的内容(位于与src平级的config资源包下)

  */

student=com.xxx.generic.demo.student

teacher=com.xxx.generic.demo.teacher

 

/**

  *beanfactory类的参考代码

  */

import java.io.inputstream;

import java.util.enumeration;

import java.util.hashmap;

import java.util.map;

import java.util.properties;

import java.util.set;

 

public class beanfactory {

  private beanfactory() {

  }

 

  private static map<string, string> beans = new hashmap<>();

  static {

  inputstream is = beanfactory. class .getclassloader().getresourceasstream( "beans.properties" );

  properties prop = new properties();

  try {

   prop.load(is);

   enumeration<string> keys = (enumeration<string>) prop.propertynames();

   while (keys.hasmoreelements()) {

   string key = keys.nextelement();

   string value = prop.getproperty(key);

   beans.put(key, value);

   }

  } catch (exception e) {

   e.printstacktrace();

  } finally {

   if (is != null ) {

   try {

    is.close();

   } catch (exception e) {

    e.printstacktrace();

   }

   }

  }

  }

 

  public static <t> t getbean( class <t> clazz) {

  t t = null ;

  string classname = clazz.getsimplename();

  set<string> keys = beans.keyset();

  for (string key : keys) {

   if (key.equals(classname)) {

   string value = beans.get(key);

   try {

    t = (t) class .forname(value).newinstance();

   } catch (exception e) {

    e.printstacktrace();

   }

   break ;

   }

  }

  return t;

  }

}

 

/**

  *beantest类参考代码

  */

public class beantest {

  public static void main(string[] args) {

  student s = beanfactory.getbean(student. class );

  system.out.println(s + ":我是" + s.getclass().getsimplename() + "的一个对象。" );

  teacher t = beanfactory.getbean(teacher. class );

  system.out.println(t + ":我是" + t.getclass().getsimplename() + "的一个对象。" );

  }

}

运行结果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/qq_41815326/article/details/81612291

查看更多关于使用BeanFactory实现创建对象的详细内容...

  阅读:36次