1.定义School类
package top.wyyblog.DI;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author wyyblog.top
* 与@Component注解相同,但意义不同的注解还有三个
* @Repository:注解在Dao实现类上
* @Service:注解在Service实现类上
* @Controller:注解在SpringMVC 的处理器上
*
*/
@Component("school") //表示当前类被Spring容器所管理
public class School {
@Value("极速学院")
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "School [name=" + name + "]";
}
}
2.定义Student类
package top.wyyblog.DI;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Scope("prototype") //多例的
@Component("student")
public class Student {
@Value("张三")
private String name;
@Value("23")
private int age;
//域属性注入
/* 1.
*@Autowired //byType方式的注解注入
*/
/* 2.
*@Autowired //byName方式的注解注入
*@Qualifier("school") //要求@Autowired和@Qualifier联合使用
*/
/* 3.
* @Resource(name="school") byName方式
* @Resource byType方式
*/
@Resource(name="school")
private School school;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSchool(School school) {
this.school = school;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", school=" + school + "]";
}
}
3.完善配置文件applicationContext.xml,开启扫描
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- bean definitions here -->
<context:component-scan base-package="top.wyyblog.DI" />
</beans>
4.测试Demo
package top.wyyblog.DI;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("top/wyyblog/DI/applicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println(student);
}
}
5.文件结构