14-MoreOnConfiguration Flashcards
Ways to read a property from the application.properties
- Using @Value(“${propertyName}”)
- @Autowired Environment env;
then: env.getProperty(“propertyName”);
How to use @Value to set a default value if property not found?
@Value(“${propertyName: default Value}”)
What properties are loaded into Spring Environment?
- Environment variables i.e. system environment variables
- Java system properties
- Additional resources added by:
@Configuration
@PropertySource(“classpath:/com/app.properties”)
@PropertySource(“file:/config/local.properties”)
class Config {} - ## Properties configured with @TestPropertySource will have higher precedence than those loaded from the OS’s env or Java system propertiesNote that if the same property is defined in both files, the value in the last one seen wins
What class does evaluate @Value expression?
PropertySourcesPlaceHolderConfigurer
It extends BFPP (BeanFactoryPostProcessor)
How to declare a BFPP bean method?
BFPP bean method must be static so that it can load before all other beans e.g.
@Configuration
class Config {
@Bean
public static PropertySourcesPlaceHolderConfigurer method() {}
}
What happens if using @Profile annotation on configuration class?
Everything (e.g. bean) in configuration belongs to the profile
How to enable a bean excepts 1 profile?
@Profile(“!profileName”)
@Bean
BeanType method() {}
Ways to activate some profiles?
- -Dspring.profiles.active=p1,p2
- System.setProperty(“spring.profiles.active”, “p1,p2”)
- In application.properties
spring.profiles.active=p1,p2 - Create applicationContext manually then set:
applicationContext.getEnvironment().setActiveProfiles(“p1,p2”); - In test
@ActiveProfiles(“p1,p2”)
class TestClass {}
Ways to create an ApplicationContext manually
- new ClassPathXmlApplicationContext(“config.xml”)
- ## new AnnotationConfigApplicationContext(ConfigClass.class)Note: WebApplicationContext is an interface
How to control property files loaded using @Profile?
@Configuration
@Profile(“local”)
@PropertyResouce(“file.properties”)
class Config {}
Expressions language implemented in Spring
- SpEL (start with #)
2. Unified Expression Language used by JSP and JSF (start with $)
How to set (daily.limit * 2) using @Value?
Must use SpEL, not work for Unified EL e.g. @Value("#{new Integer(environment["daily.limit"] * 2}")
Ways to set fall-back value using @Value?
- SpEL @Value(“#{environment[‘daily.limit’] ?: 100000}”)
2. Unified EL @Value(“${daily.limit : 100000}”)
List out default implicit references in SpEL?
- environment
- systemProperties
- systemEnvironment
What do SpEL expressions starting with $ reference?
Properties in the application environment
–> seem they mean syntax of Unified Expression Language is also supported in SpEL