Return to site
🍃🎓 SPRING CERTIFICATION QUESTION: Which are valid ways to load external properties in Spring?
🍃🎓 SPRING CERTIFICATION QUESTION: Which are valid ways to load external properties in Spring?
·
Which are valid ways to load external properties in Spring?
Using @PropertySource annotation
Using @Property annotation
Using @Value annotation
Using @Env annotation
Answer:
✅ You can load external properties with @PropertySource .
Ex:
@Configuration @PropertySource("classpath:/com/organization/config/app.properties") @PropertySource("file:config/local.properties") public class ApplicationConfig { // ... }
✅ You can also load external properties with @Value .
Ex:
@Configuration public class DbConfig { @Bean public DataSource dataSource { // convenient alternative to explicitly using Environment bean @Value("$(db.driver") String driver, @Value("$(db.url") String URL, @Value("$(db.user") String user, @Value("$(db.password") String pwd) { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName( driver ); ds.setUrl(url); ds.setUser(user); ds.setPassword(pwd); return ds; } }
❌ There is no such @Env annotation but usually, you load the environment with @Autowired:
@Autowired
private Environment env;❌ Property is not an annotation, it is a class used to handle beans properties:
Person person = new Person(); person.setName("John"); Property nameProperty = PropertyAccessorFactory.forBeanPropertyAccess(person) .getProperty("name"); System.out.println("Name: " + nameProperty.getValue());
#spring #certificationquestion #vcp