Spring框架之IOC的基本配置

前言

上一章我们学习了Spring的IOC特性以及IOC的实现原理:注解和反射,本章我们将学习如何在Spring中使用IOC。

Spring的IOC配置

Spring最重要的特性是IOC控制反转,利于IOC我们能降低对象之间的耦合性。

IOC需要通过一定的配置实现,配置方法分为:

1)使用xml文件配置

2)使用注解配置

使用Spring的基本功能,必须先导入Spring的依赖:

1. <dependency>

2. <groupId>org.springframework</groupId>

3. <artifactId>spring-context</artifactId>

4. <version>5.1.5.RELEASE</version>

5. </dependency>

Spring Context:向 Spring框架提供上下文信息。Spring 上下文包括企业服务,例如JNDI、EJB、电子邮件、国际化、校验和调度功能。它包含Spring Core组件,能实现IOC的核心功能。

使用xml文件配置

6. /**

7. * CPU接口

8. */

9. public interface Cpu {

10. void run();

11. }

12. /**

13. * AMD的CPU

14. */

15. public class AMDCpu implements Cpu {

16. public void run() {

17. System.out.println("AMD的CPU正在运行....");

18. }

19. }

20. /**

21. * 内存接口

22. */

23. public interface Memory {

24. void read();

25. void write();

26. }

27. /**

28. * DDR8G的内存

29. */

30. public class DDR8GMemory implements Memory {

31. public void read() {

32. System.out.println("使用DDR8G的内存读取数据....");

33. }

34. public void write() {

35. System.out.println("使用DDR8G的内存写入数据....");

36. }

37. }

38. 类似的IntelCpu和DDR16Memory类省略了代码

39. /**

40. * 电脑类

41. */

42. public class Computer {

43.

44. private Cpu cpu;

45. private Memory memory;

46. private String brand;

47. ...省略get\set

48. public Computer() {

}

public Computer(String brand, Cpu cpu, Memory memory) {

this.brand = brand;

this.cpu = cpu;

this.memory = memory;

}

public void start(){

System.out.println(brand+"电脑启动了");

cpu.run();

memory.read();

memory.write();

}

49. }

在maven项目的resources目录下,添加配置文件:

applicationContext.xml

50. <?xml version="1.0" encoding="UTF-8"?>

51. <beans xmlns="http://www.springframework.org/schema/beans"

52. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

53. xmlns:context="http://www.springframework.org/schema/context"

54. xsi:schemaLocation="http://www.springframework.org/schema/beans

55. http://www.springframework.org/schema/beans/spring-beans.xsd

56. http://www.springframework.org/schema/context

57. http://www.springframework.org/schema/context/spring-context.xsd">

58. <!-- CPU对象-->

59. <bean id="cpu" class="com.qianfeng.springioc.demo3.IntelCpu"/>

60. <!--Memory对象-->

61. <bean id="memory" class="com.qianfeng.springioc.demo3.DDR16GMemory"/>

62. <!--电脑对象-->

63. <bean id="computer" class="com.qianfeng.springioc.demo3.Computer">

64. <!--属性的注入-->

65. <property name="cpu" ref="cpu"></property>

66. <property name="memory" ref="memory"></property>

67. <property name="brand" value="小米电脑"></property>

68. </bean>

69. </beans>

配置说明:

<beans>是根标签,代表Spring的Java对象容器

<bean>标签代表在容器中创建一个Java对象,属性id代表对象名,class是对象的类型。

在配置文件中首先创建了一个cpu对象和一个memory对象,然后创建了一个computer对象,computer中有Cpu类型的cpu属性和Memory类型memory属性以及String类型的brand属性,这里使用依赖注入的方式给属性赋值。

<property name="cpu" ref="cpu"></property>

property 指的是对象的属性,name是属性名,ref是对象引用,这里引用了前面的cpu对象。

<property name="brand" value="华硕电脑"></property>

brand属性注入的是数值而不是对象引用,这里使用value注入值。

Spring上下文对象

Spring容器可以看做是一个JavaBean的工厂BeanFactory,BeanFactory负责创建并保存各个JavaBean,BeanFactory的子类有:

1)ClassPathXMLApplicationContext

基于XML配置文件上下文

2)AnnotationConfigApplicationContext

基于注解配置的上下文

3)FileSystemApplicationContext

基于文件系统的上下文

使用ClassPathXMLApplicationContext的方法:

70. public class TestComputer {

71.

72. @Test

73. public void testComputer(){

74. //创建XML文件的应用程序上下文对象

75. ClassPathXmlApplicationContext cxt =

76. new ClassPathXmlApplicationContext("applicationContext.xml");

77. //通过类型从容器获得Java对象

78. Computer computer = cxt.getBean(Computer.class);

79. //还可以通过对象名获得对象

80. // Computer computer = (Computer) cxt.getBean("computer");

81. computer.start();

82. }

83. }

need-to-insert-img

使用注解配置

Spring的IOC也可以不使用配置文件,完全通过Java代码和注解实现配置,这种配置方法代码更加简洁。

常用注解:

@Component

配置到类上面,Spring容器会自动扫描并添加有该注解类的对象

@Autowired

配置到属性或set方法上,容器会将容器中同类型的对象自动注入到属性中

@Qualifier

用于给不同的组件设置标识,用于区分多个相同类型的对象

@Value

注入一般类型的值,如:@Value(20) 、 @Value("张三")

@Configuration

加在配置类上,该类作为Spring启动的入口

@ComponentScan

和@Configuration配合使用,加在配置类上,用于扫描包中所有@Component注解的类

84. 在DDR8Memory类和IntelCpu类上添加@Component注解

85. 修改Computer类:

86. @Component

87. public class Computer {

88.

89. @Value("苹果电脑")

90. private String brand;

91.

92. @Autowired

93. private Cpu cpu;

94.

95. @Autowired

96. private Memory memory;

97. ....

98. }

99.

100. @Configuration

101. @ComponentScan("com.qianfeng.springioc.demo4")

102. public class MyConfig {

103.

104. public static void main(String[] args) {

105. //创建基于注解的上下文对象

106. AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext(MyConfig.class);

107. //获得Computer对象

108. Computer computer = cxt.getBean(Computer.class);

109. computer.start();

110. }

111. }

need-to-insert-img

总结

本章我们学习了两种Spring的配置方法,XML配置的好处是:和代码耦合性低,容易维护,注解配置的好处是:代码简洁。两种配置方法的优势互补,在实际开发过程中一般会使用XML和注解混合进行配置。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,593评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,080评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,025评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,317评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,329评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,036评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,639评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,557评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,089评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,197评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,330评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,006评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,689评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,189评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,313评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,676评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,339评论 2 358

推荐阅读更多精彩内容