Config: via XML or Annotation

XML配置文件的每一个bean对应Annotation方式每一个java类,property name对应类字段,ref对应引用的其他类
XML配置和注解本质上相同,创建容器时用不同的应用上下文: ClassPathXmlApplicationContext
AnnotationConfigApplicationContext, 传递参数分别为: XML文件 和 类对象

XML

config.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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-4.0.xsd ">

<bean id="course" class="com.ssm.chap9.pojo.Course">
<property name="module" ref="module" />
</bean>

<bean id="module" class="com.ssm.chap9.pojo.Module">
<property name="assignment" ref="assignment" />
</bean>

<bean id="assignment" class="com.ssm.chap9.pojo.Assignment" />
</beans>

main:

1
2
3
4
5
6
7
public class DemoCourse {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("config.xml");
Course course = ctx.getBean(Course.class);
course.getName();
}
}

Annotation

AppContextCourse.java: 基于java配置和上面XML达到和上面XML相同的效果:

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
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppContextCourse {

@Bean
public Course course() {
Course course = new Course();
course.setModule("someModule");
return course;
}

@Bean
public Module module() {
Module module = new Module();
module.setAssignment("someAssignment");
return module;
}

@Bean
public Assignment assignment() {
return new Assignment();
}
}

main:

1
2
3
4
5
6
7
public class DemoCourse {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppContextCourse.class);
Course course = ctx.getBean(Course.class);
course.getName();
}
}

突然的感悟

Spring IoC的本质:

实际上是用XML配置文件控制javaBean的生产,而不用改java代码; “不写java代码”这一点,对应不用new主动创建对象而是用配置文件配置对应被动地生成对象,就是“控制反转”说法的来历;相当于“即插即拔”

而实际上,用java代码注解配置更多:annotation; 但是本质没有变: 没有用”new”创建Bean对象,所以用XML或者注解并没有影响IoC的实现


VVV below: not important

3 classes:

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
public class Assignment {

}

public class Module {

private String assignment;

public String getAssignment() {
return assignment;
}

public void setAssignment(String assignment) {
this.assignment = assignment;
}
}

public class Course {

private String module;
private String name; // course name

public String getModule() {
return module;
}

public void setModule(String module) {
this.module = module;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}