Spring config file


package com.luv2code.springdemo;

public interface Coach {

public String getDailyWorkout();

public String getDailyFortune();

}
package com.luv2code.springdemo;

public interface FortuneService {

public String getFortune();
}
package com.luv2code.springdemo;

public class BaseballCoach implements Coach {

// define a private field for the dependency
private FortuneService fortuneService;

// define a constructor dependency injection
public BaseballCoach(FortuneService fortuneService) {
this.fortuneService = fortuneService;
}

@Override
public String getDailyWorkout() {
return "Spend 30 minutes on batting practice";
}

@Override
public String getDailyFortune() {
// use my fortuneService to get a fortune
return fortuneService.getFortune();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!-- define the dependency -->
<bean id="myFortune" class="com.luv2code.springdemo.HappyFortuneService">
</bean>

<bean id="myCoach" class="com.luv2code.springdemo.BaseballCoach">
<!-- set up constructor injection -->
<constructor-arg ref="myFortune"/>
</bean>

</beans>
What happens behind the scenes?
Spring creates objects of beans:
HappyFortuneService myFortune = new HappyFortuneService();
BeseballCoach myCoach = new BaseballCoach(myFortune);

Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class