1、 Spring DI Made by Michael.Shi 281481047@ 注入方法 2 1.Setter注入 2 2.Constructor注入 2 3.接口注入(了解) 2 简单属性注入 3 Bean的声明周期 3 1.Sigleton 3 2.Prototype 3 集合注入 3 AutoWire 4 byName 4 byType 5 LifeCycle 5 lazy-init 5 init-method和destory-method 5 Annotation 6 Autowire & Qual
2、ifier 6
1.普通xml文件 6
2.DTD BEAN 的xml文件 7
Resource 8
Component 8
全文都是以《学生课程管理》这个例子来进行说明,简单明了:
里面有studentDao,studentDaoImpl,Student,
StudentService
注入方法
1.Setter注入
在StudentService类中要有Student对象作为局部变量,以及它的setter方法
5、 name="id">
7、
8、
11、s.xml中查找名字一样的bean(student),然后进行装配。
byType
12、default” 就是依据
13、tory-method不要和prototype一起用
14、scope是sigleton那么就算是两个bean对象也只会调用一次init;但是如果scope是prototype, 那么就会调用两次init。
Annotation
Autowire好像只能用ApplicationContext,用BeanFactory会抛出异常(不清楚是什么原因,有知道的情联系我)。
& Qualifier
1.普通xml文件
(1).需要在xml中加入
15、
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.sprin 16、gframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
17、public void setStudentDao (StudentDao studentDao) { this. studentDao = studentDao; } ③.可以在构造方法上面加 @Autowired public StudentService(StudentDao studentDao) { this. studentDao = studentDao; } ④.可以在普通方法上面加 @Autowired public void addStudent(Student student) { System.out.pri
18、ntln(student.getName());
}
2.DTD BEAN 的xml文件
Xml的文件头不变,只需要添加
19、ionBeanPostProcessor, PersistenceAnnotationBeanPostProcessor RequiredAnnotationBeanPostProcessor 注意:如果autowire默认是byType,如果xml文件中有两个是同样的类型需要被注入(用非Annotation法会抛出异常),这里需要在参数上面添加@Qualifier @Autowired public void setStudentDao (@Qualifier("student2") StudentDao studentDao) 注意:@Qualifier("stu
20、dent2")中的"student2"是可以在xml的bean中配置的,
21、变量和setter方法上面进行@Resource
@Resource(name="student2")
public void addUser(Student student)
{
}
默认是byName,找不到的时候再byType,可以用(name=”student2”)来指定用哪一个同类型的bean。
Component
使用@Component能够在xml文件中不配置任何bean
1.在xml文件中添加
22、kage 指的是从哪个包中找你要的bean 这样就可以将xml文件中的bean都删除掉 2.在bean所代表的类上面加上@Component @Component public class Student { … } 3.在需要这个bean的地方可以用@Resource进行注入 @Resource public void addUser(Student student) { … } 完成! 注意:一般推荐在@Component上面加上name:@Component("student"),然后再@Resource(name="stude
23、nt"),这样能够更加清楚、准确地进行定位。 提示:也可以在xml文件中删除studentService 的bean,在StudentService的类上加上@Component("studentService") ,最后在main方法中依然使用context.getBean(“studentService”); 注意: 1.可以在@Component上面添加@Scope("prototype")来指定bean的范围(prototype / sigleton) 2.在方法上面加@PostConstruct 可以指定bean的init方法; 在方法上面加@PreDestroy可以指定bean的destory方法。






