使用到的注解

使用到的注解有@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;

/**
* @author LeDao
* @company
* @create 2022-02-13 21:26
*/
public class Student {

private int id;
private String name;


/**
* 无参构造方法,如果不存在有参构造方法时可以省略,存在就需要自己写出来
*/
public Student() {

}

/**
* 有参构造方法
*
* @param id
* @param name
*/
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;

/**
* @author LeDao
* @company
* @create 2022-02-14 1:12
*/
@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;

/**
* @author LeDao
* @company
* @create 2022-02-12 15:56
*/
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);
}
}