详细链接:https://my.oschina.net/guangshan/blog/1807721
配置类
//@Configuration
@Component
public class MyConfig {
@Bean
public Driver getDriver(){
Driver driver = new Driver();
driver.setCar(getCar());
driver.setName("詹姆斯");
return driver;
}
@Bean
public Car getCar(){
Car car = new Car();
car.setName("詹姆斯");
return car;
}
}
==============
测试类:
@SpringBootTest
@RunWith(SpringRunner.class)
class ConfigurationApplicationTests {
@Autowired
private Person person;
@Autowired
private Car car;
@Autowired
private Driver driver;
@Test
void contextLoads() {
}
@Test
public void person(){
System.out.println(person.toString());
}
@Test
public void myConfig(){
boolean b = driver.getCar() == car;
System.out.println(b?"一样":"不一样");
}
}
使用@Component 打印不一样,也就是两个car是不一样的
使用@Configuration打印结果是一样,也就是两个car是同一个
两个同时使用时打印结果是一样,说明同时使用时起作用的是@Configuration