实体类: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;
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;
import org.springframework.context.annotation.Configuration;
@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 {
@Resource(name = "dog_1") Dog dog_1;
@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}
|