第一步:引入jar包(这里是在前面的基础上添加的,就是多引入一个aop的jar包)
第二步:配置文件引入约束(context约束)
这个约束是注解开发所必须的
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
第三步:配置注解包扫描(扫描哪些包下的注解)
<context:component-scan base-package="com.ctbu"/>
第四步:在类上和属性上写上注解
@Component("student") //相当于是配置文件中配置时 bean中的id属性
public class Student {
private String name;
private String age;
private String sex;
public String getName() {
return name;
}
@Value("花木兰") //相当于是配置文件中配置的时候,属性的注入
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
@Value("23")
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
@Value("女")
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
第五步:编写测试类
@Test
public void test2(){
//加载配置文件
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取配置的对象,通过配置文件中的id
Student student = (Student) applicationContext.getBean("student");
System.out.println(student);
}