Monday, December 14, 2020

Bean Configuration without XML only JAVA CODE

 We can achieve this by creating a configuration class. The configuration class will have the following syntax


@Configuration

public class SportConfig {


The configuration annotation tells spring that this is a spring config class. We then need to add the component scanning annotation which will tell Spring which package to scan for components


@Configuration

@ComponentScan("com.rogersentongo.springdemo")

public class SportConfig{


With this we can simply replace ClassPathXml.... with AnnotationConfigApplicationContext in our main file when building the configuration object.

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SportConfig.class);


Further more we can configure each bean individually in the configuration file. We do this by eliminating the componentscan annotation(not necessary) and simply creating a bean annotation methods that inject dependencies


@Configuration

//@ComponentScan("com.rogersentongo.springdemo")... we can also leave this in as it wont be used

public class SportConfig{

//Dependency bean

@Bean

public FortuneService happyFortuneService()

{ return new HappyFortuneService();}


//Implementation Bean

@Bean

public Coach swimCoach()

{return new SwimCoach(happyFortuneService());}


In the implementation for Coach, we need to ensure that the constructor initializes the dependency.



Furthermore we can insert data from properties file by adding the @PropertySource annotation:

Given property file containing:

foo.email = rs@gmail.com

foo.team = bearcats


@Configuration

@ComponentScan("com.rogersentongo.springdemo")

@PropertySource("classpath:sport.properties")

public class SportConfig{


With this we can initialize private fields in our implementations like this

@Value("${foo.email}")

private String email;


@Value("${foo.team}")

private String team;





No comments:

Post a Comment