02-Spring-Core-Dependency Injection

Views:
 
Category: Education
     
 

Presentation Description

Explaining core part of spring framework.

Comments

Presentation Transcript

Spring Framework - Core: 

Spring Framework - Core “If you can't explain it simply, you don't understand it well enough” Albert Einstein

Topics: 

Topics Dependency Injection ( DI) Beans and Container Bean Scopes Bean Life Cycle Method Injection Best Practices Parent-Child Beans External Config Properties and Property Editors p namespace and util schema

PowerPoint Presentation: 

Dependency Injection (DI)

Dependency Injection (DI): 

Dependency Injection (DI) A kind of Inversion of Control ( IoC ) “ Hollywood Principle ” – Don't call me, I'll call you “Container ” resolves (injects) dependencies of components by setting implementation object ( push ) as opposed to component instantiating or Service Locator pattern where component locates implementation ( pull)

Types of Dependency Injection: 

Types of Dependency Injection Constructor Dependency Injection Dependencies are provided through the constructors of the component. Setter D ependency I njection Dependencies are provided through the JavaBeanstyle setter methods of the component.

Constructor Dependency Injection: 

Constructor Dependency Injection package examples; public class ExampleBean { private int years; private String ultimateAnswer; public ExampleBean(int years, String ultimateAnswer) { this.years = years; this.ultimateAnswer = ultimateAnswer; } } <bean id="exampleBean" class="examples.ExampleBean"> <constructor- arg index="0" value="7500000 "/> <constructor- arg index="1" value="42"/> </ bean>

Setter Dependency Injection: 

Setter Dependency Injection public class SetterInjection { private Dependency dep; public void setMyDependency(Dependency dep) { this.dep = dep; } } <bean id=“setterInjection" class="examples SetterInjection"> <property name="dep" ref="accountDao"/> </bean> <bean id=“accountDao" class="examples.AccountDao">

PowerPoint Presentation: 

Beans and Container

Beans and Container: 

Beans and Container Bean An object that is instantiated, assembled, and managed by a Spring IoC container. An application consist of many collaborating beans. Container Represented by BeanFactory and ApplicationContext interfaces . Responsible for instantiating, configuring, and assembling of beans.

How it works?: 

How it works?

Sample Configuration file: 

Sample 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-3.0.xsd"> < bean id="petStore" class=" org.springframework.samples.jpetstore.services.PetStoreServiceImpl "> < property name="accountDao" ref="accountDao"/> < property name=" itemDao " ref=" itemDao "/> </bean> < bean id="accountDao" class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapAccountDao </ bean> < bean id=" itemDao " class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapItemDao"> </ bean> </beans>

BeanFactory Interface: 

BeanFactory Interface BeanFactory object is responsible for managing beans and their dependencies. Your application interacts with Spring's DI container through BeanFactory interface BeanFactory object has to be created by the application typically in the form of XmlBeanFactory. BeanFactory object, when it gets created, read bean configuration file and performs the wiring. Once created, the application can access the beans via BeanFactory interface.

ApplicationContext Interface: 

ApplicationContext Interface Extension of BeanFactory interface. It provides all the same functionality and more supports to enable lots of enterprise-specific features such as transactions and AOP. Used in a more framework-oriented style by using layering and hierarchical contexts providing extra features over BeanFactory.

Using Containers: 

Using Containers // create and configure beans ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"}); // retrieve configured instance PetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.class); // use configured instance List userList service.getUsernameList();

Beans Instantiation: 

Beans Instantiation Instantiation with a constructor < bean id="exampleBean" class="examples.ExampleBean"/> Instantiation with a static factory method < bean id=" clientService " class=" examples.ClientService " factory-method=" createInstance "/> Instantiation using an instance factory method < bean id=" clientService " factory-bean=" serviceLocator " factory-method=" createClientServiceInstance "/>

PowerPoint Presentation: 

Bean Scopes

Bean Scopes: 

Bean Scopes Singleton Single object instance per Spring IoC container. Prototype Any number of object instances per Spring IoC container. Request Single object instance per Http Request. Session Single object instance per Http Session. Global Session Single object instance per Global Http Session.

Singleton: 

Singleton Default scope. Single instance per container and per bean as opposed to single instance per class loader.

Prototype: 

Prototype Destruction lifecycle callback methods are not called on prototypes.

Request: 

Request Available only in web-aware Spring ApplicationContext implementations. Bean definition <bean id=" loginAction " class=" com.foo.LoginAction " scope="request"/>

Session: 

Session Available only in web-aware Spring ApplicationContext implementations. Bean definition <bean id="userPreferences" class=" com.foo.UserPreferences " scope="session"/>

Global Session: 

Global Session Available only in context of portlet-based web applications Bean definition <bean id=" userPreferences“ class =" com.foo.UserPreference" scope="globalSession"/>

PowerPoint Presentation: 

Bean Life Cycle

Initialization Callback: 

Initialization Callback Achieved by implementing org.springframework.beans.factory.InitializingBean interface. void afterPropertiesSet() throws Exception ; OR OR Annotated method with @PostConstruct

Destruction Callback: 

Destruction Callback Achieved by implementing org.springframework.beans.factory.DisposableBean interface. void destroy() throws Exception; OR OR Annotated method with @ PreDestroy

ApplicationContextAware Interface: 

ApplicationContextAware Interface Class is provided with ApplicationContext automatically. Used for retrieval of beans. (Should be avoided)

BeanNameAware Interface: 

BeanNameAware Interface Class is provided with ApplicationContext automatically. Used for retrieval of beans. (Should be avoided)

BeanNameAware Interface: 

BeanNameAware Interface Class is provided with a reference to the name defined in its associated object definition.

Bean Life Cycle: 

Bean Life Cycle

PowerPoint Presentation: 

Method Injection

Method Injection: 

Consider a case where - Singleton bean has a dependency over prototype bean. Method Injection

Method Injection: 

Method Injection

PowerPoint Presentation: 

Autowiring

Autowiring: 

Container resolves dependency automatically by inspecting the contents of application context. If matching bean not found, property remains unwired. Limitations: Hard to debug. Reduces XML code at the cost of readability. Either all attributes or none. (Only XML based Autowiring) Autowiring

Autowiring - Types: 

Autowiring - Types

Autowiring - Examples: 

Autowiring - Examples

PowerPoint Presentation: 

Annotations

XML-based vs. Annotation-based: 

XML-based vs. Annotation-based XML-based Configuration Autowiring - Wires all properties. Wiring components without touching the source code. Beans remain POJOs. Centralized location for all configurations and easier to determine dependencies graph. Annotation-based Configuration Autowiring - Can wire specific properties. Shorter and Concise Configurations. Beans no longer POJOs. Configuration becomes decentralized and harder to control. Best Practice: Each approach has its pros and cons. Developer dependant. Annotation-based Configurations are preferred. Spring as a framework is moving towards Annotation based approach . Note : Annotation injection is performed before XML injection so XML injection will override any changes done by Annotation injection.

Annotations: 

Annotations Annotations require few Post Processors to be registered with the container . Following post processors are implicitly registered by using <annotation- config > tab. AutowiredAnnotationBasedBeanPostProcessor CommonAnnotationBeanPostProcessor PersistenceAnnotationBeanPostProcessor RequiredAnnotationBeanPostProcessor

@Required: 

@Required Annotation to make the injection through given setter mandatory. Indicates bean property mandatory – Set either by XML or annotation. Applicable to bean property setter methods. Target – Setter Methods.

@Autowired: 

@Autowired Annotation to make the injection through given setter mandatory. Annotation to automatically wire a dependency. Autowiring by Type - @Autowired and @Autowired (required=false) Default behavior – Mandatory dependencies. Target – Setters, Methods, Constructors, Attributes.

@Qualifier: 

@Qualifier Provide control over the selection from multiple candidates shortlisted for Autowiring. @Qualifier – Wire the candidate with the qualifier name same as present in annotation. Duplicate qualifier names allowed. Default – Bean name is considered as default qualifier value. Target – Fields, Parameters, Type, Annotation Type

JSR-250 Annotations: 

JSR-250 Annotations @Resource Same as @Autowired but JSR compliant @ PostConstruct and @ PreDestroy Initialization callback and Destruction callback.

Component Scanning: 

Component Scanning Explicit Definition: Every bean declared manually in configuration file. What if Spring automatically detects the components? Container scans the candidate components in classpath . Spring supports: @Component – Basic Annotation @Repository – Components in Persistence Layer (Adds the error handler automatically) @Service – Components in Service Layer @Controller – Components in Presentation Layer

Component Scanning (Contd..): 

Component Scanning (Contd..) Naming Convention: Default: Same as class name but the first alphabet in lowercase. Name: Bean name can be passed as parameter to annotations. For ex: @Service(<bean name>) Scanning can be customized by applying include/exclude filters. Scanning Annotations not required if a class is defined in include-filter. Types Annotation – Annotation type Assignable - Class/Interface for filtering Regex – Regular Expression Aspectj – Pointcut expression matching the classes

@Configuration and @Bean: 

@Configuration and @Bean Used for moving configurations from XML to Java. @Configuration Class is used by the Spring container as the source of bean definitions . @Bean Annotate a factory method that returns a new bean. Bean definitions are java beans annotated with @Bean. Classpath Requirements: Cglib.jar Asm.jar

@Qualifier: 

@Qualifier Annotation to make the injection through given setter mandatory. Indicates bean property mandatory – Set either by XML or annotation. Applicable to bean property setter methods. Target – Setter Methods.

PowerPoint Presentation: 

Best Practices

Best Practices: 

Prefer ApplicationContext over BeanFactory ApplicationContext supports i18n, Resource Loading and Events. BeanFactory preferred when there is limitation on resources and size of application. For ex. Applets, Mobile Applications. Bean Naming Convention Use clear, descriptive naming convention for beans Recommendation: CamelCase . Use Java naming convention for classes with first alphabet in lowercase Inner Beans. Use when bean only available to a parent bean Use <null/> or null property Best Practices

Best Practices: 

Split the configuration in different xml files. Minimal one xml file per architectural layer. Prefer assembling beans (multiple xmls ) through ApplicationContext over imports . Every bean must have an id or name. No anonymous bean. Id attribute makes XML parsers validate the bean . Prefer Annotation based Autowiring over XML based. Add @Qualifier annotation wherever required to make the code more readable. Best Practices