开始前,在maven中导入spring-context依赖
@Configuration使用:加在类的上方,表示当前类是作为配置文件使用的,就是用来配置容器的。
相当于Spring的配置文件beans.xml
为了进行测试,先创建一个Student类
package org.example.vo;
public class Student {
private String name;
private Integer age;
private String sex;
//getter setter
//toString
}
创建一个SpringConfig类,在类名上方加上@Configuration,并在类中写入方法
@Configuration
public class SpringConfig {
@Bean
public Student createStudent(){
Student s1=new Student();
s1.setAge(16);
s1.setName("zs");
s1.setSex("男");
return s1;
}
}
进行测试:
@Test
public void test02(){
ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfig.class);
//若没有指定属性名,则默认为方法名
Student student=(Student)ac.getBean("createStudent");
System.out.println(student);
}
结果:



