在Spring入门一中通过ApplicationContext.xml配置文件来实现IOC,在本篇中将通过Annotation来是实现控制反转。
1.导入响应的jar包或添加响应的依赖:spring-aop-…。
2.在配置文件中添加包扫描。
<context:component-scan base-package="com" ></context:component-scan>
3.在实体类上添加注释,可以自动地对该类创建对象。
com包下的实体类1
@Component//该单词一位部件、元件、构建
public class Teacher {
private String name;
private int age;
public Teacher() {
}
public Teacher(String name, int age) {
this.name = name;
this.age = age;
}
//get、set、toString方法省略
}
com包下的实体类2:
@Component
public class Student {
private String name;
private int age;
private char sex;
@Autowired//意思为自动装配,也就是teacher这个引用会指向一个自动创建的Teacher对象
private Teacher teacher;
public Student() {
}
public Student(Teacher teacher)
{
this.teacher=teacher;
}
public Student(String name, int age, char sex, Teacher teacher) {
this.name = name;
this.age = age;
this.sex = sex;
this.teacher = teacher;
}
//get、set、toString方法省略
}
@Component注释的源码:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
String value() default "";
}
该注释只能放在类上面。value的值相当于getBean中的字符串,用来获取对象。在修饰Student的Component中填写value值为“st”,main方法中的代码如下:
public class Demo01 {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml");
Student stu=(Student) context.getBean("st");
System.out.println(stu);
}
}
@Autowired源码:
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
这个注释可以放到类上,方法上,成员变量上。因此除了将该注释放到私有的tea上外,还可以将该注释放到setTea(Teacher tea)方法上。效果是一样的。
测试类的写法:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/ApplicationContext.xml")
public class MyTest {
@Autowired
private Student stu;//自动实例化对象,不需要在Component中给出value的值
@Test
public void show()
{
System.out.println(stu);
}
}
getBean的两种重载方法:
- 传入类的类名,但是首字母要小写。getBean("student");
- 传入类名点class。getBean(Student.class);
用 java显示配置:实体类和用注释配置的一致。类上加@Component,在引用变量上或set方法上加@AutoWired。除此之外,再新建一个java类。内容如下:
@Configuration//配置
public class springConfig {
@Bean("s")
public Student getStudent()
{
return new Student();
}
@Bean
public Teacher getTeacher()
{
return new Teacher();
}
}
main方法:
public class Demo01 {
public static void main(String[] args) {
ApplicationContext context=new AnnotationConfigApplicationContext(springConfig.class);
Student stu=(Student) context.getBean("s");
System.out.println(stu);
}
}
上一篇 |
---The End---
| 下一篇 |