使用到的注解
使用到的注解有@Configuration
和@Bean
@Configuration
标注在类上,相当于把该类作为Spring的XML配置文件中的beans标签
@Bean
标注在方法上(返回某个实例的方法),等价于Spring的XML配置文件中的bean标签,用于注册bean对象,如果没有定义name属性那么bean的id为方法名,定义了name属性那么bean的id为name的属性值(这时候就不可以用方法名了)
实现过程
Student实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| package entity;
public class Student {
private int id; private String name;
public Student() {
}
public Student(int id, String name) { this.id = id; this.name = name; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
|
Spring配置类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package config;
import entity.Student; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
@Configuration public class MyConfig {
@Bean(name = "s1") public Student tom111() { Student student = new Student(); student.setId(111); student.setName("tom111"); return student; } }
|
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import config.MyConfig; import entity.Student; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); Student student = (Student) context.getBean("s1"); System.out.println(student); } }
|