问题遇到的现象和发生背景
描述一下就是,首先用@Bean直接注入一个Person对象,
接着再用@ConfigurationProperties+@EnableConfigurationProperties(Person.class)进行属性绑定,
@EnableConfigurationProperties(Person.class)注解会往容器中注入一个Person的实体bean。
这两个bean在容器中的名称不一样,
一个是@Bean修饰的方法名的小写-->personImpl;
另一个是person-com.springboot2.learn.bean.Person。
然后我用getBean的方法取这两个对象,输出都是Person(name=张三, age=20)。
这两个bean显然不是同一个,使用@ConfigurationProperties+@EnableConfigurationProperties(Person.class)注解注入的实体Bean的属性绑定这是毋庸置疑的,让我困惑的是使用@Bean注入的bean为什么也和配置文件中的内容进行了绑定?
问题相关代码,请勿粘贴截图
//实体bean:Person
package com.springboot2.learn.bean;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ToString
@NoArgsConstructor
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
}
//Application.java
package com.springboot2.learn;
import com.springboot2.learn.bean.Person;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
@EnableConfigurationProperties(Person.class)
public class Application {
public static void main(String[] args) {
//获取IOC容器
ConfigurableApplicationContext run = SpringApplication.run(Application.class, args);
//获取容器中的bean的名字
String[] beanDefinitionNames = run.getBeanDefinitionNames();
for (String name:beanDefinitionNames
) {
System.out.println(name);
}
//使用@Bean注解注入的Person组件
Person personImpl = (Person) run.getBean("personImpl");
System.out.println("使用@Bean注解注入的Person:" + personImpl);
Person bean = (Person) run.getBean("person-com.springboot2.learn.bean.Person");
System.out.println("使用属性绑定注入的Person:" + bean);
System.out.println(personImpl==bean);
}
}
//配置类MyConfig.java
package com.springboot2.learn.config;
import com.springboot2.learn.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
@Bean
public Person personImpl(){
Person person = new Person();
return person;
}
}