Spring Tutorial Notes

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
  • AnnotationConfigApplicationContext
  • GenericWebApplicationContext
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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容