Entity:
@Component
public class Person {
@Value("zhangsan")
private String name;
@Value("20")
private Integer age;
}
Config的一个方法:
@Bean
Person getPerson() {
Person person1 = new Person("lisi", 21);
return person1;
}
测试类的方法:
@Test
public void contextLoads() {
ApplicationContext ioc = new AnnotationConfigApplicationContext(MyApplicationConfiguration.class);
Person person = (Person) ioc.getBean("getPerson");
System.out.println(person);
Person person1 = (Person) ioc.getBean("person");
System.out.println(person1);
System.out.println(person == person1);
System.out.println(person.getClass() == person1.getClass());
}
输出结果:
Person{name='zhangsan', age=20}
Person{name='zhangsan', age=20}
false
true
我想问,既然两个Person对象不是同一个,为什么值会一样?求大神解释解释
确实不是同一个,值一样是因为@Value注解的原因。
是这样的,getPerson方法中虽然调用构造方法设置了person1的值,并返回,
但是spring拿到这个对象之后,看到你的@Value注解,会通过反射重新给person1的属性赋值(zhangsan,20)
这样两个person属性就是一样的了。