注解注入annotation
注意重点内容
要想用annotation必须在applicationContext.xml中加入 命名空间
<!-- 要想用注解注入 ,必须加入这三条
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
-->
applicationContext.xml中文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="person" class="com.example.vic.test_spring.di_annotation.Person">
</bean>
<bean id="student" class="com.example.vic.test_spring.di_annotation.Student">
</bean>
<!-- 会先遍历 bean中的类 寻找@resource 然后匹配其中的name 然后注入 -->
<context:annotation-config></context:annotation-config>
</beans>
public class Person {
public Person() {
System.out.println("new person");
}
@Resource(name="student")
private Student student;
@PostConstruct //在构造器之后
//然后注解注入就在这个init()之后
public void init(){
System.out.println("init");
}
@PreDestroy //在spring容器销毁之前
public void destroy(){
System.out.println("destroy");
}
public void sys(){
this.student.say();
}
}
public class Student {
public Student() {
System.out.println("new Student");
}
public void say() {
System.out.println("student");
}
}