@Configuration注解表明这个类是一个配置类。可以启动组件扫描,用来将带有@Bean的实体进行实例化bean等
把普通pojo实例化到spring容器中,相当于配置文件中的 <bean id="" class=""/>
结论
package com.fan.utils.environment;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @author およそ神
* @version JDK 1.8
*/
@Component
public class MyTestConfig {
@Bean
public Driver driver(){
Driver driver = new Driver();
driver.setId(1);
driver.setName("driver");
driver.setCar(car());
return driver;
}
@Bean
public Car car(){
Car car = new Car();
car.setId(1);
car.setName("car");
return car;
}
}
package com.fan;
import com.fan.utils.environment.Car;
import com.fan.utils.environment.Driver;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author およそ神
* @version JDK 16
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {
@Autowired
private Car car;
@Autowired
private Driver driver;
@Test
public void contextLoads() {
Car car = driver.getCar();
boolean result = car == this.car;
System.out.println(result ? "同一个car" : "不同的car");
}
}
Configuration是同一个对象,Component不是同一个对象
当使用Configuration注解或者@component,并实体类使用了@data注解时,是同一个对象.
当使用Configuration注解或者@component,但是实体类不使用了@data注解时,不是同一个对象.