Repository navigation
Spring Configuration using java code
Java Configuration(No XML!)
-
• Instead of configuring Spring container using XML
-
• Configure the Spring container with Java code
-
Development Process
-
- Create a Java class and annotate as @Configuration
-
- Add component scanning support: @ComponentScan (optional)
-
- Read Spring Java configuration class
-
- Retrieve bean from Spring container
Step 1: Create a Java class and annotate as @Configuration
@Configuration
public class SportConfig {
}
Step 2: Add component scanning support @CommponentScan (Optional Step)
@Configuration
@ComponentScan("com.luv2code.springdemo")
public class SportConfig {
}
Step 3: Read Spring Java configuration class
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(SportConfig.class);
Step 4: Retrieve bean from Spring container
Coach theCoach = context.getBean("tennisCoach", Coach.class);
Development Process
-
- Define method to expose bean
-
- Inject bean dependencies
-
- Read Spring Java configuration class
-
- Retrieve bean from Spring container
Step 1: Define method to expose bean
@Configuration
public class SportConfig {
@Bean
public Coach swimCoach() {
SwimCoach mySwimCoach = new SwimCoach();
return mySwimCoach;
}
}
Step 2: Inject bean dependencies
@Configuration
public class SportConfig {
@Bean
public FortuneService happyFortuneService() {
return new HappyFortuneService();
}
@Bean
public Coach swimCoach() {
SwimCoach mySwimCoach = new SwimCoach( happyFortuneService() );
return mySwimCoach;
}
}
Step 3: Read Spring Java configuration class
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(SportConfig.class)
Step 4: Retrieve bean from Spring container
Coach theCoach = context.getBean("swimCoach", Coach.class);
Development Process
-
- Create Properties File
-
- Load Properties File in Spring config
-
- Reference values from Properties File
Step 1: Create Properties File sport.properties (inside src folder)
foo.email=myeasycoach@luv2code.com
foo.team=Awesome Java Coders
Step 2: Load Properties file in Spring config File : sportConfig.java
@Configuration
@PropertySource("classpath:sport.properties")
public class SportConfig {
…
}
Step 3: Reference Values from Properties File
File : SwimCoach.java
public class SwimCoach implements Coach {
@Value("${foo.email}")
private String email;
@Value("${foo.team}")
private String team;
...
}