SpringBoot的Bean

实体类:Dog.java

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
package club.swzdl.springboot.domain.entities;
/*
* @Author Sheng WenZeng
* @Date 2019/9/22 22:50
* @Version 1.0
*/

/**
* @author Sheng Wenzeng
* @ClassName Dog
* @Description TODO
* @Date 2019/9/22 22:50
* @Version 1.0
*/
public class Dog {
private String name;
private int age;

public int getAge() {
return age;
}

void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}

public String getName() {
return name;
}

void setName(String name) {
this.name = name;
}
}

相当于 Spring 的 xml 配置文件BeanConfigOfDog.java

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
package club.swzdl.springboot.domain.entities;/*
* @Author Sheng WenZeng
* @Date 2019/9/22 22:14
* @Version 1.0
*/

import org.springframework.context.annotation.Configuration;

/**
* @author Sheng Wenzeng
* @ClassName Dog
* @Description TODO
* @Date 2019/9/22 22:14
* @Version 1.0
*/

/*
* 本文件就相当于 Spring 的 xml 配置文件,相当于 Dog.java 的 Spring 配置文件
*/
@Configuration
public class BeanConfigOfDog {

@org.springframework.context.annotation.Bean()
public Dog dog_1() {
Dog dog = new Dog();
dog.setName("Tom");
dog.setAge(1);
return dog;
}

@org.springframework.context.annotation.Bean()
public Dog dog_2() {
Dog dog = new Dog();
dog.setName("Jack");
dog.setAge(2);
return dog;
}
}

两种装配方式:入口函数:SpringBootApplication.java

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
package club.swzdl.springboot;

import club.swzdl.springboot.domain.entities.Dog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@SpringBootApplication
@RestController
public class SpringbootApplication {

/*
* 指定要装配的 Bean 的名字
*/
@Resource(name = "dog_1")
Dog dog_1;

/*
* 自动装配,默认与名字相同,即注入名为 dog_2 的 Bean
*/
@Autowired
Dog dog_2;

public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}

@RequestMapping("/getBeans")
public String getBeans() {
System.out.println(dog_1.toString());
System.out.println(dog_2.toString());
return "";
}
}

运行结果

1
2
Dog{name='Tom', age=1}
Dog{name='Jack', age=2}

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×