Spring框架的全部教程,详细点这里
使用注解的方式完成注入对象中的效果
- 修改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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" 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.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config /><!-- 告诉Spring要用注解的方式配置 -->
<bean name="s" class="com.bean.Student">
<property name="name" value="Student" />
</bean>
<bean name="t" class="com.bean.Teacher">
<property name="name" value="Teacher" />
<!-- <property name="student" ref="s" />注释掉这句 -->
</bean><!-- 以上:注入对象行为注解 -->
</beans>
2.在Teacher.java的Student属性前加上@Autowired注解
package com.bean;
public class Teacher {
private int id;
private String name;
// 添加Autowired注解,也可以在setStudent()位置加注解,效果一样
@Autowired
private Student student;
}
3.运行测试
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
// System.out.println("test page !!!");
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
// 通过Spring拿到的Student对象的name属性
// Student s1 = (Student) context.getBean("s");
// System.out.println(s1.getName());
Teacher t = (Teacher) context.getBean("t");
t.setName("teacher--1");
t.setStudent(new Student("student--1"));
System.out.println(t.getName());
System.out.println(t.getStudent().getName());
}
}
对Bean的注解
1、修改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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" 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.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.bean"/>
<!-- 告诉Spring,bean都放在com.bean这个包下-->
</beans>
2、为Student、Teacher类加上@Component注解,即表明此类是bean
@Component("s")
public class Student
@Component("t")
public class Teacher
3、 运行测试通上