@ConfigurationProperties和@Bean创建对象的时候并根据属性名称注入配置文件中的属性值。
对象;
@Data
@ToString
public class TestBean {
String name;
int age;
String date;
}
注入属性:
import com.zhong.spring.usuldemo.bean.TestBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestBeanConfig {
@Bean("testBean")
@ConfigurationProperties(prefix = "test.data")
public TestBean testBean(){
return new TestBean();
}
}
测试:
@Component
public class TestBeanCommandLineRunner implements CommandLineRunner {
@Autowired
TestBean testBean;
@Override
public void run(String... strings) throws Exception {
System.out.println(testBean.toString());
}
}
结果: