Friday, 11 November 2016

Inversion of Control(IoC) and Dependency Injection(DI)

IoC is a design principle, and DI is its implementation. Its main purpose, in my understanding, is to avoid instantiating instances within classes, i.e. aggregation or composition, a sort of strong association.

Traditionally, the logic is controlled by a custom-written code, where reusable procedures or modules are invoked in a sequence. By this way, the independent units have to become dependent on each other. Certainly, those independent units can be manipulated in a container, where they can be externally instantiated in runtime as they are invoked. It is a way to decouple the dependencies of units.

Spring framework provides this sort of IoC container. It instantiates Java plain classes(also called Spring beans) in runtime and giving references to their consumers. It is termed dependency injection(DI), which can be configured in ether a configuration class or by a xml file located in the source folder. It declares which implementation should be instantiated as in runtime,

In Spring there are two ways to configure this sort of external instantiation, i.e. in a Spring context where a bean is instantiated and ready by accessed by the client code. Which bean should be instantiated in such a Spring context, it is a client responsibility to define. It could be defined in a XML file located in source folder; or in a configuration class decorated by annotations.

a. by a configuration class

package Configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import services.EmailService;
import services.MessageService;

@Configuration
@ComponentScan(value={"Consumer"})
public class DIConfiguration {
 @Bean
 public MessageService getMessageService(){
  return new EmailService();
 }
}

b. by a XML configuration file. 

 <?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
      <bean id="MyXmlApplication" class="Consumer.MyXMLApplication">  
           <constructor-arg>  
                <bean class="services.TwitterService"></bean>  
           </constructor-arg>  
      </bean>  
 </beans>  

No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...