就是装载bean三种方法:
xml装载
通过注解装配 Bean
通过隐式 Bean 的发现机制和自动装配的原则
第一种不经常使用了,我就不讲了
第二种:通过注解装配 Bean
package pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component(value = "student1")
public class Student {
@Value("1")
int id;
@Value("student_name_1")
String name;
// getter and setter
}
需要用到@component和@value
@componnent是用来生成bean对象
@value是用来装载数据的
在xml表示
<bean name="student1" class="pojo.Student">
<property name="id" value="1" />
<property name="name" value="student_name_1"/>
</bean>
但是现在我们声明了这个类,并不能进行任何的测试,因为 Spring IoC 并不知道这个 Bean 的存在,这个时候我们可以使用一个 StudentConfig 类去告诉 Spring IoC :
package pojo;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
public class StudentConfig {
}
@ComponnentScan是标志
这个类十分简单,没有任何逻辑,但是需要说明两点:
- 该类和 Student 类位于同一包名下
- @ComponentScan注解:
代表进行扫描,默认是扫描当前包的路径,扫描所有带有@Component
注解的 POJO。
然后定义SpringIOC容器的实现类
ApplicationContext context = new AnnotationConfigApplicationContext(StudentConfig.class);
Student student = (Student) context.getBean("student1", Student.class);
student.printInformation();