Spring——依赖注入的注解解析器



      
      
      
      
      
      
      






 

Student类

package cn.itcast.spring01.scan;

public class Student {

	public void say() {
		System.out.println("student");
	}
}


 

Person类

package cn.itcast.spring01.scan;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Person {
	@Resource(name="student")
	//下面两个注解就相当于@Resource,他们是spring自己发明的
//	@Autowired
//	@Qualifier(value="student")
	private Student student;
	
	public void say(){
		this.student.say();
	}
	
	//下面这样写,在配置文件中就不需要写init-method和destory-method
//	@PostConstruct
//	public void init(){
//		System.out.println("init");
//	}
//	@PreDestroy
//	public void desctory(){
//		System.out.println("desctory");
//	}
}


 

PersonTest测试类

package cn.itcast.spring01.scan;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersonTest {
	@Test
	public void test(){
		ApplicationContext context = new ClassPathXmlApplicationContext("cn/itcast/spring01/di/annotation/applicationContext.xml");
		Person person = (Person)context.getBean("person");
		person.say();
	}
}


 

你可能感兴趣的:(后端)