[Spring]: Java Configuration
spring
09/12/2019
Methods to create a spring container
- Full XML Config
- Java Annotation
- Java Configuration Class (No XML needed)
Java Configuration (No XML)
- Instead of configuring Spring contaner using XML, we can configure the Spring container only with Java code
Below two steps are the same as Java Annotation (2nd method)
@Configuration
Create a Java class and annotate as @Configuration
JAVA
@Configurationpublic class PlayerConfig {
}
@ComponentScan(optional)
- Add component scanning support
JAVA
@Configuration@ComponentScan("com.ellismin") // package to scanpublic class PlayerConfig {
}
Read Spfing Java config class (new!) in main method
JAVA
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PlayerConfig.class);
- Different from ClassPathXmlApplicationContext since we don't use xml file anymore
Retrieve bean from spring contaner (same as previous)
JAVA
Player player = context.getBean("swimPlayer", Player.class);
Define bean in Java config class (@Bean)
Defining bean is possible in the Java configuration class. These beans can be used without @ComponentScan
JAVA
@Configurationpublic class PlayerConfig { // Create instance of SunnyWeather and return it @Bean public Weather sunnyWeather() { return new sunnyWeather(); } // Define bean for swim player AND inject dependency @Bean public Player swimPlayer() { SwimPlayer mySwimPlayer = new SwimPlayer(); return mySwimPlayer; }}
- sunnyWeather and swimPlayer will be the "bean id". This will be used when retriving the bean (in previous step)
- @Scope("ScopeName") can be added under @Bean for particular scoped beans
Reading values from properties file (@PropertySource)
- In xml configuration or Java annotation, it needed a piece of code
- With Java config, it can be achieved with @PropertySource in Java config class
JAVA
@Configuration@PropertySource("emailList.properties")public class PlayerConfig { ...}
- To obtain the value, it will be done in the same way as Java Annotations with @Value
JAVA
public class BasketballPlayer implements Player { @Value("${john.email}") private String email; ...}