Spring Certified Professional 2023 · Free Practice Question Hard
Question 4
Which snippet binds foo.properties to Foo bean?
Consider Foo having :
- private long id;
- private String name;
-
A
- @Component
- @ConfigurationProperties("classpath:foo.properties")
- public class FooProperties {
- @PropertySource(prefix = "foo")
- private Foo foo;
- // getters and setters
- }
-
B
- @Configuration
- @PropertySource("classpath:foo.properties")
- public class FooProperties {
- @ConfigurationProperties(prefix = "foo")
- private Foo foo;
- // getters and setters
- }
-
C
- @Component
- @ConfigurationProperties
- @PropertySource("classpath:foo.properties")
- public class Foo {
- private long id;
- private String name;
- // ...
- // getters and setters
- }
-
D
- @Configuration
- @PropertySource("classpath:foo.properties")
- public class FooProperties {
- @ConfigurationProperties(name = "foo")
- private Foo foo;
- // getters and setters
- }
Reveal correct answer
Correct answer: C
Explanation
ConfigurationProperties and PropertySource cannot be applied to a field.
So the only right answer is
- @Component
- @ConfigurationProperties
- @PropertySource("classpath:foo.properties")
- public class Foo {
- private long id;
- private String name;
- // ...
- // getters and setters
- }
https://mkyong.com/spring-boot/spring-boot-configurationproperties-example/
Spring doc:
* public @interface ConfigurationProperties
Annotation for externalized configuration. Add this to a class definition or a @Bean method in a @Configuration class if you want to bind and validate some external Properties (e.g. from a .properties file).
* public @interface PropertySource
Annotation providing a convenient and declarative mechanism for adding a PropertySource to Spring's Environment. To be used in conjunction with @Configuration classes.
- @Configuration
- @PropertySource("classpath:/com/myco/app.properties")
- public class AppConfig {
- @Autowired
- Environment env;
- @Bean
- public TestBean testBean() {
- TestBean testBean = new TestBean();
- testBean.setName(env.getProperty("testbean.name"));
- return testBean;
- }
- }
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
