Spring Tutorial Notes

2019-01-13  本文已影响0人  梦元_38ab

Inversion of Control

Step1: Configure the Spring beans

<beans...>
  <bean id="myCoach"
        class="com.luv2code.springdemo.BaseballCoach">
  </bean>

</beans

Step 2: Create a Spring Container / ApplicationContext
The containner is used to create and manage the objects(inversion of control), inject object's dependencies(Dependency Injection). The container could be implemented as below:

ClassPathXmlApplicationContext context = new ClassPathXmlApplication("applicationContext.xml")

Step 3: Retrieve Beans from Containers

Coach theCoach = context.getBean("myCoach", Coach.class);

Dependency Injection

Step 1: Define the dependency interface and class

public interface FortuneService{
    public String getFortune();
}

public class HappyFortuneService implements FortuneService{
    public String getFortune(){
            return "Today is your lucky day"
    } 
}

Step 2: Create a constructor & Setter in your class for injections

public class BaseballCoach implements Coach{
    private Fortune fortuenService;

    public BaseballCoach(FortuneService theFortuneService){
            fortuneService = theFortuneService;
    }
          
    public BaseballCoach(){}
        
    public void setFortuneService(FortuneService fortuneService){  
          this.fortuneService = fortuneService;
    }
}

Step 3. Configure the dependency injection in Spring config file

<bean id="myFortune"
        class="com.luv2code.springdemo.HappyFortuneService">
</bean>

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

<!--Setter Injection-->
<bean id="myCoach"
    class="com.luv2code.springdemo.BaseballCoach">
    <property name="fortuneService" ref="myFortune">            
 </bean>
上一篇下一篇

猜你喜欢

热点阅读