SlideShare a Scribd company logo
1 of 117
Download to read offline
Spring Framework - Core




                SPRING FRAMEWORK 3.0
Dmitry Noskov   Spring Core
What is Spring?
Spring is the most popular application development
framework for enterprise Java™. Millions of
developers use Spring to create high performing,
easily testable, reusable code without any lock-in.




                       Spring Framework - Core   Dmitry Noskov
The Spring projects

                                           Spring
                                            MVC

                     Spring                                 Spring
                     Social                                WebFlow




         Spring                                                       Spring
         Batch                                                       Security
                                           Spring
                                         Framework



            Spring                                                Spring
             Data                                              Integration



                               Spring
                                Web
                                                     And
                              Services               …

                                   Spring Framework - Core           Dmitry Noskov
Overview
History
Goals
Spring modules
Spring triangle




                  Spring Framework - Core   Dmitry Noskov
Spring Framework history(1)
   the first version was written by Rod Johnson
   Expert One-on-One J2EE Design and Development
   first released in June 2003
   milestone releases in 2004 and 2005
   awards
     Jolt productivity award
     JAX Innovation award




                           Spring Framework - Core   Dmitry Noskov
Spring Framework history(2)
   Spring 3.0 (released Dec 2009)
     Java 1.5+
     REST support, SpEL, more annotations, JavaConfig

   Spring 2.5 (released Nov 2007)
     Java 1.4+
     XML namespaces, annotations

   Spring 2.0 (released Oct 2006)
     Java 1.3+
     AspectJ support, JPA

                             Spring Framework - Core   Dmitry Noskov
Goals
   make J2EE easier to use
   make the common tasks easier
   promote good programming practice
   you can focus on the domain problems




                       Spring Framework - Core   Dmitry Noskov
What is Spring Framework today?
   an open source application framework
   a lightweight solution for enterprise applications
   non-invasive (POJO based)
   is modular
   extendible for other frameworks
   de facto standard of Java Enterprise Application




                         Spring Framework - Core   Dmitry Noskov
Spring modules




                 Spring Framework - Core   Dmitry Noskov
Core container
   Core and Beans
provide the fundamental parts of the framework, including IoC and Dependency
Injection features

   Context
it is a means to access objects in a framework-style manner that is similar to a JNDI
registry

   Expression language
provides a powerful expression language for querying and manipulating an object
graph at runtime




                                      Spring Framework - Core   Dmitry Noskov
AOP, Aspect, Instrumentation
   AOP
provides an AOP Alliance-compliant aspect-oriented programming implementation
allowing you to define, for example, method-interceptors and pointcuts to cleanly
decouple code that implements functionality that should be separated

   Aspect
provides integration with AspectJ

   Instrumentation
provides class instrumentation support and classloader implementations to be used in
certain application servers




                                     Spring Framework - Core   Dmitry Noskov
Data Access/Integration
   JDBC - provides a JDBC-abstraction layer
   ORM - provides integration layers for popular object-relational mapping APIs,
    including JPA, JDO, Hibernate and iBatis

   OXM - provides an abstraction layer that supports Object/XML mapping
    implementations for JAXB, Castor, XMLBeans, JiBX and XStream.

   JMS – contains features for producing and consuming messages.
   Transaction - supports programmatic and declarative transaction
    management




                                     Spring Framework - Core   Dmitry Noskov
WEB
   Spring’s WEB
provides basic web-oriented integration features

   WEB-Servlet
Spring’s model-view-controller (MVC) implentation

   WEB-Struts
contains the classes for integrating a classic Struts WEB tier within a Spring application

   WEB-Portlet
provides the MVC implementation to be used in a portlet environment




                                       Spring Framework - Core   Dmitry Noskov
Full-fledged Spring web application




                Spring Framework - Core   Dmitry Noskov
Using a third-party web framework




              Spring Framework - Core   Dmitry Noskov
Remoting




           Spring Framework - Core   Dmitry Noskov
EJB




      Spring Framework - Core   Dmitry Noskov
The Spring triangle




               Spring Framework - Core   Dmitry Noskov
Spring IoC container
IoC pattern
Application lifecycle
Essence of Spring IoC container
Instantiation an ApplicationContext




                   Spring Framework - Core   Dmitry Noskov
What is IoC?
   is a concept in application development
   "don’t call me, I’ll call you"
   one form is Dependency Injection (DI)




                        Spring Framework - Core   Dmitry Noskov
Dependency Injection
   is a process whereby objects define their
    dependencies, that is, the other objects they work
    with, only through constructor arguments, arguments
    to a factory method, or properties that are set on
    the object instance after it is constructed or returned
    from a factory method
   exist in two major variants
         1) constructor injection
         2) setter injection
                          Spring Framework - Core   Dmitry Noskov
IoC vs DI vs Factory
   DI it is specific type of IoC

   The Factory pattern’s main concerns is creating
   The DI’s main concern is how things are connected
    together

   DI related to Factory and Strategy patterns, but
    mostly resembles to Build Pattern

                           Spring Framework - Core   Dmitry Noskov
Application lifecycle


Initialization    Use                             Destruction

   • creating    • process                             • shuts
     services      requests                              down
   • allocate    • 99% of                              • release
     resources     the time                              resources




                 Spring Framework - Core   Dmitry Noskov
Essence of IoC container




               Spring Framework - Core   Dmitry Noskov
Terms
   ApplicationContext
       represents the Spring IoC container
   bean
       is an object that managed by Spring IoC container
   BeanDefinition
       describe a bean instance




                            Spring Framework - Core   Dmitry Noskov
Context lifecycle




   Load        BFPP   Instantiation      Property            BPP     Ready
 definitions                             injection                   to use




                           Spring Framework - Core   Dmitry Noskov
Bean lifecycle




                 Spring Framework - Core   Dmitry Noskov
Creating application context
   environments
     standalone
     WEB

     JUnit

     EJB

   special prefixes
     classpath
     file system

     relative path

                       Spring Framework - Core   Dmitry Noskov
Instantiation for standalone
   ClassPathApplicationContext
   FileSystemApplicationContext
ApplicationContext context =
    new ClassPathXmlApplicationContext(
     new String[] {"services.xml", "repositories.xml"});


// retrieve configured instance
CurrencyService currencyService
         = context.getBean("currency", CurrencyService.class);


AccountService accountService
         = context.getBean(AccountService.class);


                               Spring Framework - Core   Dmitry Noskov
Instantiation for WEB applications

Servlet 2.4+                                               Servlet 2.3
<context-param>
                                                           <servlet>
 <param-name>
  contextConfigLocation                                      <servlet-name>
 </param-name>
                                                              context
 <param-value>
  /WEB-INF/daoContext.xml                                    </servlet-name>
  /WEB-INF/applicationContext.xml
                                                             <servlet-class>
 </param-value>
                                                           org.springframework.web.context.ContextLoaderServlet
</context-param>
                                                             </servlet-class>
<listener>
                                                             <load-on-startup>1
  <listener-class>
org.springframework.web.context.ContextLoaderListener        </load-on-startup>
  </listener-class>
                                                           </servlet>
</listener>




                                                  Spring Framework - Core    Dmitry Noskov
Bean Scope
Simple
Runtime
WEB
CGLIB / JDK proxies




                 Spring Framework - Core   Dmitry Noskov
Spring Bean Scopes
   simple
       singleton
       prototype
   runtime
       thread
       custom implementation
   web-aware scopes (available only for web-aware ApplicationContext)
       request
       session
       global session

                                   Spring Framework - Core   Dmitry Noskov
The singleton scope




               Spring Framework - Core   Dmitry Noskov
The prototype scope




              Spring Framework - Core   Dmitry Noskov
Custom scope

public interface org.springframework.beans.factory.config.Scope {
    //Return the object with the given name from the underlying scope
    Object get(String name, ObjectFactory<?> objectFactory);


    //Remove the object with the given name from the underlying scope.
    Object remove(String name);


    //Register a callback to be executed on destruction of the specified object
    void registerDestructionCallback(String name, Runnable callback);


    //Resolve the contextual object for the given key, if any.
    Object resolveContextualObject(String key);


    //Return the conversation ID for the current underlying scope, if any.
    String getConversationId();
}

                                       Spring Framework - Core   Dmitry Noskov
Using runtime scope
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
 <property name="scopes">
   <map>
      <entry key="thread">
          <bean class="org.springframework.context.support.SimpleThreadScope"/>
      </entry>
   </map>
 </property>
</bean>


<bean id="threadService" class="example.ThreadServiceImpl" scope="thread">
 <property name="priority" value="0"/>
 <aop:scoped-proxy/>
</bean>


<bean id="threadMonitor" class="example.ThreadMonitorImpl">
 <property name="threadService" ref="thredService"/>
</bean>



                                       Spring Framework - Core   Dmitry Noskov
Scoped bean as dependencies

Using CGLIB library (by default)
<bean id="preferences" class="UserPreferences" scope="session">
  <aop:scoped-proxy/>
</bean>
<bean id="userManager" class="example.UserManager">
  <property name="userPreferences" ref="preferences"/>
</bean>

Using JDK interface based proxies means
<bean id="preferences" class="UserPreferences" scope="session">
  <aop:scoped-proxy proxy-target-class="false"/>
</bean>
<bean id="userManager" class="example.UserManager">
  <property name="userPreferences" ref="preferences"/>
</bean>


                                   Spring Framework - Core   Dmitry Noskov
WEB-aware scope configuration

Servlet 2.4+                                  Servlet 2.3
<web-app>                                     <web-app>
<listener>                                      <filter>
                                                 <filter-name>filter</filter-name>
 <listener-class>
                                                 <filter-class>
org.springframework.web.context.request.
RequestContextListener                           …web.filter.RequestContextFilter
 </listener-class>                               </filter-class>
</listener>                                     </filter>
</web-app>                                      <filter-mapping>
                                                 <filter-name>filter</filter-name>
                                                 <url-pattern>/*</url-pattern>
                                                </filter-mapping>
                                              </web-app>


                                     Spring Framework - Core   Dmitry Noskov
XML-based configuration
Configuration
Main features
Bean lifecycle
Additional features




                  Spring Framework - Core   Dmitry Noskov
Namespaces
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">


  <bean id="" class=""></bean>

  <bean id="" class=""/>
</beans>


                                  Spring Framework - Core   Dmitry Noskov
BeanFactoryPostProcessor

public interface BeanFactoryPostProcessor {

    /**
     * Modify the application context's internal bean factory after its standard
     * initialization. All bean definitions will have been loaded, but no beans
     * will have been instantiated yet. This allows for overriding or adding
     * properties even to eager-initializing beans.
     * @param beanFactory the bean factory used by the application context
     * @throws org.springframework.beans.BeansException in case of errors
     */
     void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory);
}




                                   Spring Framework - Core   Dmitry Noskov
Instantiating bean


                     Spring Framework - Core   Dmitry Noskov
Naming beans

<beans>
  <bean id="beanId" class="org.exhanger.api.OrderServiceImpl"/>


  <bean name="name/" class="org.exhanger.api.OrderServiceImpl"/>


  <bean name="name1,name2;name3 name4" class="...">
  </bean>


  <alias name="fromName" alias="toName"/>
</beans>



                            Spring Framework - Core   Dmitry Noskov
Instantiating bean
   with a constructor
   with a static factory method
   using an instance factory method
   with the FactoryBean




                        Spring Framework - Core   Dmitry Noskov
Instantiating with a constructor
   simple class
<bean id="exampleBean" class="examples.ExampleBean"/>
public class ExampleBean {
    public ExampleBean() {}
}

   inner class
<bean id="innerBean" class="examples.ExampleBean$InnerBean"/>
public class ExampleBean {
    public static class InnerBean {
    }
}



                              Spring Framework - Core   Dmitry Noskov
Instantiating with a static method

<bean id="clientService" class="examples.ClientService"
         factory-method="createInstance"/>


public class ClientService {
    private static ClientService clientService = new ClientService();


    private ClientService() {}


    public static ClientService createInstance() {
        return clientService;
    }
}


                                 Spring Framework - Core   Dmitry Noskov
Using an instance factory method
<!-- the factory bean-->
<bean id="serviceLocator" class="example.ServiceLocator"/>
<!-- the bean to be created via the factory bean -->
<bean id="clientService"
         factory-bean="serviceLocator"
         factory-method="createClientServiceInstance"/>


public class ServiceLocator {
    private static ClientService clientService = new ClientService();


    public ClientService createClientServiceInstance() {
        return clientService;
    }
}

                                 Spring Framework - Core   Dmitry Noskov
Instantiating with the FactoryBean
public interface FactoryBean<T> {
    /**Return an instance of the object managed by this factory.*/
    T getObject() throws Exception;


    /** Return the type of object that this FactoryBean creates.*/
    Class<?> getObjectType();


    /**Is the object managed by this factory a singleton? */
    boolean isSingleton();
}


<bean id="bean" class="FactoryBean"/>



                                Spring Framework - Core   Dmitry Noskov
Dependency injection


                 Spring Framework - Core   Dmitry Noskov
Constructor-based DI
   is accomplished by the container invoking a
    constructor with a number of arguments, each
    representing a dependency
   calling a static factory method with specific
    arguments to construct the bean is nearly equivalent




                         Spring Framework - Core   Dmitry Noskov
Constructor argument resolution
   argument resolution
<bean id="b1" class="org.examples.ClientServiceBean">
  <constructor-arg ref="b2"/>
  <constructor-arg ref="b3"/>
</bean>

   argument type matching
<bean id="b2" class="ClientService" factory-method="getInstance">
  <constructor-arg type="int" value="7500000"/>
  <constructor-arg type="java.lang.String" value="42"/>
</bean>

   argument index
<bean id="b3" factory-bean="factory" factory-method="getInstance"/>
  <constructor-arg index="0" value="75"/>
  <constructor-arg index="1" value="42"/>
</bean>

                              Spring Framework - Core   Dmitry Noskov
Setter-based DI
   is accomplished by the container calling setter
    methods on your beans after invoking a no-
    argument constructor or no-argument static factory
    method to instantiate bean




                         Spring Framework - Core   Dmitry Noskov
Constructor vs setter
   constructor
     mandatory dependencies
     immutability

   setter
     optional dependencies and default values
     obvious names

     auto inheritance




                          Spring Framework - Core   Dmitry Noskov
Straight values

<bean id="dataSource"
      class="org.apache.commons.dbcp.BasicDataSource" >


  <!-- results in a setDriverClassName(String) call -->
  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  <property name="url">
      <value>jdbc:mysql://localhost:3306/mydb</value>
  </property>
  <property name="username" value="root"/>
  <property name="password" value="masterkaoli"/>
</bean>



                            Spring Framework - Core   Dmitry Noskov
Null and empty values
<!-- is equivalent to the following code: bean.setEmail("").-->
<bean class="Bean">
  <property name="email" value=""/>
</bean>




<!-- The <null/> element handles null values. -->
<bean class="Bean">
  <property name="email"><null/></property>
</bean>




                            Spring Framework - Core   Dmitry Noskov
properties

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations" value="classpath:jdbc.properties"/>
</bean>


<bean id="dataSource" destroy-method="close"
       class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="${jdbc.driverClass}"/>
  <property name="url" >
     <value>${jdbc.url}</value>
  </property>
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>

                                      Spring Framework - Core   Dmitry Noskov
idref
bean
<bean id="theTargetBean" class="..."/>


<bean id="theClientBean" class="...">
  <property name="targetName">
    <idref bean="theTargetBean" />
  </property>
</bean>

local
<property name="targetName">
<!--a bean with id 'theTargetBean' must exist -->
  <idref local="theTargetBean"/>
</property>


                               Spring Framework - Core   Dmitry Noskov
Reference to other bean
   bean
<ref bean="someBean"/>

   local
<ref local="someBean"/>

   parent
<!-- in the parent context -->
<bean id="accountService" class="com.foo.SimpleAccountService"/>

<!-- in the child (descendant) context -->
<bean id="accountService" class="org.springframework.ProxyFactoryBean">
  <property name="target">
    <ref parent="accountService"/>
  </property>
</bean>


                              Spring Framework - Core   Dmitry Noskov
Inner bean

<bean id="orderService" class="OrderServiceImpl">
  <property name="repository" ref="orderRepository"/>
  <property name="builder">
    <bean class="OrderBuilderImpl">
      <constructor-arg ref="accountService"/>
      <constructor-arg ref="currencyService"/>
    </bean>
  </property>
</bean>




                              Spring Framework - Core   Dmitry Noskov
Collections(1)
<!-- setAdminEmails(java.util.Properties) call -->
<property name="adminEmails">
  <props>
   <prop key="administrator">administrator@gmail.com</prop>
  </props>
</property>
<!-- setSomeList(java.util.List) call -->
<property name="someList">
  <list>
   <value>a list element followed by a reference</value>
   <ref bean="myDataSource" />
  </list>
</property>


                             Spring Framework - Core   Dmitry Noskov
Collections(2)
<!-- setSomeMap(java.util.Map) call -->
<property name="someMap">
  <map>
    <entry key="an entry" value="just some string"/>
    <entry key ="a ref" value-ref="myDataSource"/>
  </map>
</property>
<!-- setSomeSet(java.util.Set) call -->
<property name="someSet">
  <set>
    <value>just some string</value>
    <ref bean="myDataSource" />
  </set>
</property>


                            Spring Framework - Core   Dmitry Noskov
p namespace
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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="orderService" class="OrderServiceImpl"
           p:repository-ref="orderRepository"
           p:locaton="BY"/>


</beans>



                                        Spring Framework - Core    Dmitry Noskov
util namespace
<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
     http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/util
     http://www.springframework.org/schema/util/spring-util-3.0.xsd">


</beans>




                              Spring Framework - Core   Dmitry Noskov
util in action
<property name="isolation">
  <util:constant static-field="java.sql.Connection.TRANSACTION_SERIALIZABLE"/>
</property>

<bean id="testBean" class="org.springframework.beans.TestBean">
  <property name="age" value="10"/>
</bean>
<util:property-path id="name" path="testBean.age"/>

<util:properties id="" location="classpath:jdbc.properties"/>


<util:list id="emails" list-class=""><value/><value/></util:list>

<util:map id="emails" map-class=""><entry key="" value=""/></util:map>

<util:set id="emails" set-class=""><value></value></util:set>



                                    Spring Framework - Core   Dmitry Noskov
Additional features
   bean definition inheritance
   importing configuration files
   autowiring
   lazy initialization
   dependency checking




                          Spring Framework - Core   Dmitry Noskov
Bean definition inheritance

<!—attribute class is optional 
<bean id="parent" abstract="true" class="AbstractService">
  <property name="name" value="parent"/>
  <property name="age" value="1"/>
</bean>


<bean id="service" class="ServiceImpl" parent="parent">
     <property name="name" value="override it"/>
</bean>




                            Spring Framework - Core   Dmitry Noskov
Bean definition inheritance(2)
<bean id="parent" abstract="true">
  <property name="name" value="parent"/>
</bean>


<bean id="default" class="DefaultServiceImpl" parent="parent">
  <property name="name" value="default"/>
  <property name="value" value="22"/>
</bean>


<bean id="custom" class="CustomServiceImpl" parent="default">
     <property name="name" value="custom"/>
</bean>



                            Spring Framework - Core   Dmitry Noskov
Importing configuration files
   xml-context-config.xml
<beans>
    <import resource="classpath:xml-repository-config.xml"/>
    <import resource="classpath:xml-service-config.xml"/>
</beans>

   xml-service-config.xml
<beans>
    <bean id="currencyRepository" class="CurrencyMapRepository"/>
</beans>

   xml-repository-config.xml
<bean id="currencyService" class="CurrencyServiceImpl">
    <constructor-arg ref="currencyRepository"/>
</bean>


                                Spring Framework - Core   Dmitry Noskov
Using depends-on
   can explicitly force one or more beans to be
    initialized before the bean using this element is
    initialized
<bean id="beanOne" class="ExampleBean"
       depends-on="costService,accountDao">
    <property name="deviceManager" ref="deviceManager" />
</bean>


<bean id="costService" class="example.service.CostService" />
<bean id="accountDao" class="example.jdbc.JdbcAccountDao" />



                              Spring Framework - Core   Dmitry Noskov
Lazy-initialized beans
   IoC container create a bean instance when it is first
    requested
<bean id="lazy" class="ExpensiveToCreateBean" lazy-init="true"/>

   control lazy-initialization at the container level
<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>

   disadvantages
     errors in the configuration or surrounding

     environment are detected some time later

                              Spring Framework - Core   Dmitry Noskov
Autowiring
   advantages
       can significantly reduce the need to specify properties
        or constructor arguments
       can update a configuration as your objects evolve
   disadvantages
     cannot autowire simple properties (primitives)
     autowiring is less exact than explicit wiring

     wiring information may not be available to tools that
      may generate documentation from a Spring container

                             Spring Framework - Core   Dmitry Noskov
Autowiring modes
   no (default)
   byName
<bean id="messageSource" class="MessageSourceImpl" />
public void setMessageSource(MessageSource messageSource)

   byType
<bean id="messageSource" class="MessageSourceImpl" />
public void setMessageSource(MessageSource messageSource)

   constructor
   autodetect

                               Spring Framework - Core   Dmitry Noskov
Dependency checking
 none (default)
 simple

  checking for primitive types and collections
 object

  checking for collaborators only
 all




                        Spring Framework - Core   Dmitry Noskov
Spring Aware Interfaces


                 Spring Framework - Core   Dmitry Noskov
Spring aware interfaces
   BeanNameAware
   BeanFactoryAware
   ApplicationContextAware

   ApplicationEventPublisherAware
   ServletConfigAware
   ServletContextAware
   MessageSourceAware

                       Spring Framework - Core   Dmitry Noskov
Application events
public class SomeService implements ApplicationContextAware {
    public void setApplicationContext(ApplicationContext ctx) {}


    public void anyMethod(String value) {
        context.publishEvent(new AnyEvent(value));
    }
}


public class Listener implements ApplicationListener<AnyEvent> {
    public void onApplicationEvent(AnyEvent event) {
    }
}



                             Spring Framework - Core   Dmitry Noskov
Internationalization
<bean class="org.springframework.context.support.ResourceBundleMessageSource">
  <property name="basenames">
    <list><value>label</value><value>exceptions</value></list>
  </property>
</bean>

public interface MessageSource {
  /** Try to resolve the message. Return default if no message was found.*/
  String getMessage(String code, Object[] args, String default, Locale locale);

    /** Try to resolve the message. Treat an error if the message can't be found.*/
    String getMessage(String code, Object[] args, Locale locale);

    /** Try to resolve the message using MessageSourceResolvable */
    String getMessage(MessageSourceResolvable resorvable, Locale locale);
}



                                           Spring Framework - Core   Dmitry Noskov
Initialization


                 Spring Framework - Core   Dmitry Noskov
BeanPostProcessor
/**
* ApplicationContexts can autodetect BeanPostProcessor beans in their
* bean definitions and apply them to any beans subsequently created. */
public interface BeanPostProcessor {
/**
* Apply this BeanPostProcessor to the given new bean instance before any bean
* initialization callbacks (like afterPropertiesSet or a custom init-method)*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;


/**
* Apply this BeanPostProcessor to the given new bean instance after any bean
* initialization callbacks (like afterPropertiesSet or a custom init-method).
*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;


}



                                       Spring Framework - Core   Dmitry Noskov
Initialization callbacks
<bean id="bean1" class="exampl.ExampleBean1" init-method="init"/>
public class ExampleBean1 {
    public void init() {}
}


<bean id="bean2" class="examples.ExampleBean2"/>
public class ExampleBean2 implements InitializingBean {
    public void afterPropertiesSet() {}
}


public class ExampleBean2 {
    @PostConstruct
    public void initialize() {}
}


                              Spring Framework - Core   Dmitry Noskov
Destroy Spring Beans


                 Spring Framework - Core   Dmitry Noskov
Destruction callbacks
<bean id="bean1" class="example.Bean1" destroy-method="cleanup"/>
public class Bean1 {
    public void cleanup() {}
}


<bean id="bean2" class="example.Bean2"/>
public class Bean2 implements DisposableBean {
    public void destroy() {}
}


public class Bean2 {
    @PreDestroy
    public void destroy() {}
}


                               Spring Framework - Core   Dmitry Noskov
Combining lifecycle mechanisms
   initialization methods, are called as follows:
       methods annotated with @PostConstruct
       afterPropertiesSet as defined by InitializingBean
       custom configured init method
   destroy methods are called in the same order:
       method annotated with @PreDestroy
       destroy() as defined by the DisposableBean
       custom configured destroy method


                           Spring Framework - Core   Dmitry Noskov
Annotation-based configuration
Basic annotations
Spring stereotypes
JSR-250
JSR-330




                     Spring Framework - Core   Dmitry Noskov
Annotation based configuration
   an alternative to XML setups
   annotation injections is performed before XML




                        Spring Framework - Core   Dmitry Noskov
Basic annotations(1)
   Spring Annotations
     @Autowired
     @Qualifier
     @Required
     @Value
   JSR 250
     @Resource
     @PostConstruct
     @PreDestroy


                     Spring Framework - Core   Dmitry Noskov
Basic annotations(2)
   context
       @Scope
       @Bean
       @DependsOn
       @Lazy
   transactional
     @Transactional




                     Spring Framework - Core   Dmitry Noskov
Stereotypical



                          @Component
                            Any component



@Repository      @Service               @Controller             @Configuration
   Data access   Service classes           Spring MVC                 Java Config




                            Spring Framework - Core   Dmitry Noskov
Basic configuration


<!-- looks for annotations on beans -->
<context:annotation-config/>



<!– scan stereotyped classes and register BeanDefinition -->
<context:component-scan
   base-package="org.exhanger.repository.map,org.exhanger.api">




                               Spring Framework - Core   Dmitry Noskov
Basic configuration(2)
<context:component-scan
   base-package="org.exhanger"
   name-generator="my.NameGeneratorImpl"
   resource-pattern="**/*.class"
   scope-resolver="my.ScopeResolverImpl"
   scoped-proxy="no|interfaces|targetClass">


 <context:include-filter type="annotation"
     expression="org.springframework.stereotype.Service"/>
 <context:exclude-filter type="regex"
     expression=".*MapRepository"/>


</context:component-scan>


                            Spring Framework - Core   Dmitry Noskov
@Value

@Component("authenticationProvider")
public class EjbAuthenticationProvider {

    /** The provider api connection url. */
    @Value("${provider.api.url}")
    private String apiUrl;

    /** The provider api connection username. */
    private @Value("${provider.api.username}") String apiUsername;

    /** The provider api connection password. */
    @Value("${provider.api.password}")
    private String apiPassword;
}



                              Spring Framework - Core   Dmitry Noskov
@Autowired(1)
@Service("accountService")
public class AccountServiceImpl {
    @Autowired
    private AccountRepository repository;


    @Autowired
    public AccountServiceImpl(AccountRepository repository) {}


    @Autowired(required = false)
    public void setRepository(AccountRepository repository) {}


    @Autowired
    public void populate(Repository r, OrderService s) {}
}


                              Spring Framework - Core   Dmitry Noskov
@Autowired(2)
@Service
public class AccountServiceImpl {


    @Autowired
    private AccountRepository[] repositories;


    @Autowired
    public AccountServiceImpl(Set<AccountRepository> set) {}


    @Autowired(required = false)
    public void setRepositories(Map<String,AccountRepository> map){
    }
}


                              Spring Framework - Core   Dmitry Noskov
@Required(1)

public class AccountServiceImpl {
    private AccountRepository repository;


    @Required
    public void setRepository(AccountRepository repository) {}
}



<bean name="accountService" class="AccountServiceImpl">
    <property name="repository" ref="accountRepository"/>
</bean>



                              Spring Framework - Core   Dmitry Noskov
@Required(2)
public class AccountServiceImpl {
    private AccountRepository repository;


    @Mandatory
    public void setRepository (AccountRepository repository) {}
}


<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
    <property name="requiredAnnotationType" value="my.Mandatory"/>
</bean>


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Mandatory {}


                                          Spring Framework - Core   Dmitry Noskov
@Qualifier
public class ReportServiceImpl {
    @Autowired
    @Qualifier("main")
    private DataSource mainDataSource;


    @Autowired
    @Qualifier("freeDS")
    private DataSource freeDataSource;
}
<beans>
    <bean class="org.apache.commons.dbcp.BasicDataSource">
      <qualifier value="main"/>
    </bean>
    <bean id="freeDS" class="org.apache.commons.dbcp.BasicDataSource"/>
</beans>

                                  Spring Framework - Core   Dmitry Noskov
@Resource
public class AccountServiceImpl {
    @Resource(name = "orderService")
    private OrderService orderService;


    @Resource(name = "orderService")
    public void setOrderService(OrderService orderService) {}


    @Resource
    private AuditService auditService;


    @Resource
    public void setAuditService(AuditService auditService) {}
}


                              Spring Framework - Core   Dmitry Noskov
@Scope

@Service
@Scope("prototype")
public class AccountServiceImpl implements AccountService {
}



@Service
@Scope(value = BeanDefinition.SCOPE_PROTOTYPE,
       proxyMode = ScopedProxyMode.TARGET_CLASS)
public class AccountServiceImpl implements AccountService {
}



                            Spring Framework - Core   Dmitry Noskov
@Lazy & @DependsOn


@Lazy
@Service
@DependsOn({"orderService", "currencyService"})
public class AccountServiceImpl implements AccountService {
}




                            Spring Framework - Core   Dmitry Noskov
Factory method component

@Component
public class CurrencyRepositoryFactory {


    @Bean
    @Lazy
    @Scope("prototype")
    @Qualifier("public")
    public CurrencyRepository getCurrencyRepository() {
        return new CurrencyMapRepository();
    }
}



                                Spring Framework - Core   Dmitry Noskov
JSR 330
@Named
@Singleton
public class AccountServiceImpl implements AccountService {


    @Inject
    private AccountRepository repository;


    @Inject
    public AccountServiceImpl(@Named("default") AccountRepository r) {}


    @Inject
    public void setAccountRepository(AccountRepository repository) {}


}

                                Spring Framework - Core   Dmitry Noskov
@Autowired vs @Inject
Spring       JSR-330       JSR-330 restrictions
@Autowired   @Inject       has no ‘required’ attribute
@Component   @Named
@Scope       @Scope        only for meta-annotations and injection points
@Scope       @Singleton    default scope is like ‘prototype’
@Qualifier   @Named
@Value                X
@Required             X
@Lazy                 X




                          Spring Framework - Core   Dmitry Noskov
Java-based configuration
Configuration
Basic annotations




                    Spring Framework - Core   Dmitry Noskov
Instantiatiating for standalone
   simple
    new AnnotationConfigApplicationContext(ExchangerConfig.class);

   programmaticaly
    context = new AnnotationConfigApplicationContext();
    context.register(ExchangerConfig.class);
    context.refresh();

   scanning
    context = new AnnotationConfigApplicationContext();
    context.scan("org.exchanger.config");
    context.refresh();




                              Spring Framework - Core   Dmitry Noskov
Instantiating bean

@Configuration
public class ExchangerRepositoryConfg {


    @Bean(name = "accountRepository", initMethod = "init")
    public AccountRepository accountRepository() {
        return new AccountMapRepository();
    }


    @Bean
    public AuditRepository auditRepository() {
        return new AuditMapRepository();
    }
}


                                Spring Framework - Core   Dmitry Noskov
@Import

@Configuration
@Import({RepositoryConfig.class, ServiceConfig.class})
public class ExchangerConfig {
}




@Configuration
public class RepositoryConfg {}


@Configuration
public class ServiceConfig {}


                            Spring Framework - Core   Dmitry Noskov
@ImportResources
@Configuration
@ImportResource("classpath:jdbc.properties")
public class ExchangerConfig {


    @Value("jdbc.url")
    private String jdbcUrl;


    @Bean
    public DataSourse dataSource() {
        return new SimpleDataSource(jdbcUrl);
    }
}



                                Spring Framework - Core   Dmitry Noskov
Dependency injection
@Configuration
public class ExchangerServiceConfig {


    @Autowired
    private CurrencyRepository currencyRepository;


    public @Bean CurrencyService currencyService() {
        return new CurrencyServiceImpl(currencyRepository);
    }


    @Bean(name = {"orderBuilder", "builder"})
    public OrderBuilder orderBuilder() {
        return new OrderBuilder(currencyService(), accountService());
    }
}

                                  Spring Framework - Core   Dmitry Noskov
Summary
Benefits of IoC
Context lifecycle
Mix and match




                    Spring Framework - Core   Dmitry Noskov
Benefits of IoC
   minimizes the amount of code
   make application more testable
   promote programming to interfaces
   loose coupling with minimal effort
   support eager instantiation and lazy loading
   provide control over object lifecycle




                        Spring Framework - Core   Dmitry Noskov
Context lifecycle




               Spring Framework - Core   Dmitry Noskov
Approach to configuration
   XML
       infrastructure beans
   annotations
       working beans
   java
       an alternative to the FactoryBean




                               Spring Framework - Core   Dmitry Noskov
You can mix and match
   dependency injection
     constructor-based and setter-based
     you can mix and match

   configuration metadata
     XML, annotations, Java
     you can mix and match

   annotations
     own, JSR-250, JSR-330
     you can mix and match

                           Spring Framework - Core   Dmitry Noskov
Links
   site
    http://www.springsource.org/
   reference
    http://static.springsource.org/spring/docs/3.0.x/spring-
    framework-reference/html/
   blog
    http://blog.springsource.com/category/spring/
   forum
    http://forum.springsource.org/forumdisplay.php?f=26

                              Spring Framework - Core   Dmitry Noskov
Books




        Spring Framework - Core   Dmitry Noskov
Questions




            Spring Framework - Core   Dmitry Noskov
The end




             http://www.linkedin.com/in/noskovd

      http://www.slideshare.net/analizator/presentations

More Related Content

What's hot (20)

Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Spring boot
Spring bootSpring boot
Spring boot
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 

Similar to Spring Framework - Core

How Spring Framework Really Works?
How Spring Framework Really Works?How Spring Framework Really Works?
How Spring Framework Really Works?NexSoftsys
 
spring framework ppt by Rohit malav
spring framework ppt by Rohit malavspring framework ppt by Rohit malav
spring framework ppt by Rohit malavRohit malav
 
Introduction to Spring sec1.pptx
Introduction to Spring sec1.pptxIntroduction to Spring sec1.pptx
Introduction to Spring sec1.pptxNourhanTarek23
 
Spring (1)
Spring (1)Spring (1)
Spring (1)Aneega
 
04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment Workshop04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment WorkshopChuong Nguyen
 
Spring Basics
Spring BasicsSpring Basics
Spring BasicsEmprovise
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
The spring 32 update final
The spring 32 update finalThe spring 32 update final
The spring 32 update finalJoshua Long
 
Workshop OSGI PPT
Workshop OSGI PPTWorkshop OSGI PPT
Workshop OSGI PPTSummer Lu
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorialvinayiqbusiness
 
A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom Joshua Long
 
Spring Tutorial for Beginners
Spring Tutorial for BeginnersSpring Tutorial for Beginners
Spring Tutorial for BeginnersJava2Blog
 

Similar to Spring Framework - Core (20)

Spring
SpringSpring
Spring
 
Introducing spring
Introducing springIntroducing spring
Introducing spring
 
How Spring Framework Really Works?
How Spring Framework Really Works?How Spring Framework Really Works?
How Spring Framework Really Works?
 
Spring Mvc
Spring MvcSpring Mvc
Spring Mvc
 
Spring session
Spring sessionSpring session
Spring session
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
spring framework ppt by Rohit malav
spring framework ppt by Rohit malavspring framework ppt by Rohit malav
spring framework ppt by Rohit malav
 
Introduction to Spring sec1.pptx
Introduction to Spring sec1.pptxIntroduction to Spring sec1.pptx
Introduction to Spring sec1.pptx
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 
04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment Workshop04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment Workshop
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Springs_Training
Springs_TrainingSprings_Training
Springs_Training
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
The spring 32 update final
The spring 32 update finalThe spring 32 update final
The spring 32 update final
 
Workshop OSGI PPT
Workshop OSGI PPTWorkshop OSGI PPT
Workshop OSGI PPT
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorial
 
Spring notes
Spring notesSpring notes
Spring notes
 
A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom
 
Spring Tutorial for Beginners
Spring Tutorial for BeginnersSpring Tutorial for Beginners
Spring Tutorial for Beginners
 

Recently uploaded

Efficiencies in RPA with UiPath and CyberArk Technologies - Session 2
Efficiencies in RPA with UiPath and CyberArk Technologies - Session 2Efficiencies in RPA with UiPath and CyberArk Technologies - Session 2
Efficiencies in RPA with UiPath and CyberArk Technologies - Session 2DianaGray10
 
The Critical Role of Spatial Data in Today's Data Ecosystem
The Critical Role of Spatial Data in Today's Data EcosystemThe Critical Role of Spatial Data in Today's Data Ecosystem
The Critical Role of Spatial Data in Today's Data EcosystemSafe Software
 
Arti Languages Pre Seed Pitchdeck 2024.pdf
Arti Languages Pre Seed Pitchdeck 2024.pdfArti Languages Pre Seed Pitchdeck 2024.pdf
Arti Languages Pre Seed Pitchdeck 2024.pdfwill854175
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
A PowerPoint Presentation on Vikram Lander pptx
A PowerPoint Presentation on Vikram Lander pptxA PowerPoint Presentation on Vikram Lander pptx
A PowerPoint Presentation on Vikram Lander pptxatharvdev2010
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsYoss Cohen
 
Deliver Latency Free Customer Experience
Deliver Latency Free Customer ExperienceDeliver Latency Free Customer Experience
Deliver Latency Free Customer ExperienceOpsTree solutions
 
Women in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationWomen in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationDianaGray10
 
Transport in Open Pits______SM_MI10415MI
Transport in Open Pits______SM_MI10415MITransport in Open Pits______SM_MI10415MI
Transport in Open Pits______SM_MI10415MIRomil Mishra
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Bitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactiveBitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactivestartupro
 
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdf
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdfHCI Lesson 1 - Introduction to Human-Computer Interaction.pdf
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdfROWELL MARQUINA
 
Dublin_mulesoft_meetup_API_specifications.pptx
Dublin_mulesoft_meetup_API_specifications.pptxDublin_mulesoft_meetup_API_specifications.pptx
Dublin_mulesoft_meetup_API_specifications.pptxKunal Gupta
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 

Recently uploaded (20)

Efficiencies in RPA with UiPath and CyberArk Technologies - Session 2
Efficiencies in RPA with UiPath and CyberArk Technologies - Session 2Efficiencies in RPA with UiPath and CyberArk Technologies - Session 2
Efficiencies in RPA with UiPath and CyberArk Technologies - Session 2
 
The Critical Role of Spatial Data in Today's Data Ecosystem
The Critical Role of Spatial Data in Today's Data EcosystemThe Critical Role of Spatial Data in Today's Data Ecosystem
The Critical Role of Spatial Data in Today's Data Ecosystem
 
Arti Languages Pre Seed Pitchdeck 2024.pdf
Arti Languages Pre Seed Pitchdeck 2024.pdfArti Languages Pre Seed Pitchdeck 2024.pdf
Arti Languages Pre Seed Pitchdeck 2024.pdf
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
A PowerPoint Presentation on Vikram Lander pptx
A PowerPoint Presentation on Vikram Lander pptxA PowerPoint Presentation on Vikram Lander pptx
A PowerPoint Presentation on Vikram Lander pptx
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Infrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platformsInfrared simulation and processing on Nvidia platforms
Infrared simulation and processing on Nvidia platforms
 
Deliver Latency Free Customer Experience
Deliver Latency Free Customer ExperienceDeliver Latency Free Customer Experience
Deliver Latency Free Customer Experience
 
BoSEU24 | Bill Thompson | Talk From Another Century
BoSEU24 | Bill Thompson | Talk From Another CenturyBoSEU24 | Bill Thompson | Talk From Another Century
BoSEU24 | Bill Thompson | Talk From Another Century
 
Women in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationWomen in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automation
 
Transport in Open Pits______SM_MI10415MI
Transport in Open Pits______SM_MI10415MITransport in Open Pits______SM_MI10415MI
Transport in Open Pits______SM_MI10415MI
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Bitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactiveBitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactive
 
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdf
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdfHCI Lesson 1 - Introduction to Human-Computer Interaction.pdf
HCI Lesson 1 - Introduction to Human-Computer Interaction.pdf
 
Dublin_mulesoft_meetup_API_specifications.pptx
Dublin_mulesoft_meetup_API_specifications.pptxDublin_mulesoft_meetup_API_specifications.pptx
Dublin_mulesoft_meetup_API_specifications.pptx
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 

Spring Framework - Core

  • 1. Spring Framework - Core SPRING FRAMEWORK 3.0 Dmitry Noskov Spring Core
  • 2. What is Spring? Spring is the most popular application development framework for enterprise Java™. Millions of developers use Spring to create high performing, easily testable, reusable code without any lock-in. Spring Framework - Core Dmitry Noskov
  • 3. The Spring projects Spring MVC Spring Spring Social WebFlow Spring Spring Batch Security Spring Framework Spring Spring Data Integration Spring Web And Services … Spring Framework - Core Dmitry Noskov
  • 4. Overview History Goals Spring modules Spring triangle Spring Framework - Core Dmitry Noskov
  • 5. Spring Framework history(1)  the first version was written by Rod Johnson  Expert One-on-One J2EE Design and Development  first released in June 2003  milestone releases in 2004 and 2005  awards  Jolt productivity award  JAX Innovation award Spring Framework - Core Dmitry Noskov
  • 6. Spring Framework history(2)  Spring 3.0 (released Dec 2009)  Java 1.5+  REST support, SpEL, more annotations, JavaConfig  Spring 2.5 (released Nov 2007)  Java 1.4+  XML namespaces, annotations  Spring 2.0 (released Oct 2006)  Java 1.3+  AspectJ support, JPA Spring Framework - Core Dmitry Noskov
  • 7. Goals  make J2EE easier to use  make the common tasks easier  promote good programming practice  you can focus on the domain problems Spring Framework - Core Dmitry Noskov
  • 8. What is Spring Framework today?  an open source application framework  a lightweight solution for enterprise applications  non-invasive (POJO based)  is modular  extendible for other frameworks  de facto standard of Java Enterprise Application Spring Framework - Core Dmitry Noskov
  • 9. Spring modules Spring Framework - Core Dmitry Noskov
  • 10. Core container  Core and Beans provide the fundamental parts of the framework, including IoC and Dependency Injection features  Context it is a means to access objects in a framework-style manner that is similar to a JNDI registry  Expression language provides a powerful expression language for querying and manipulating an object graph at runtime Spring Framework - Core Dmitry Noskov
  • 11. AOP, Aspect, Instrumentation  AOP provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated  Aspect provides integration with AspectJ  Instrumentation provides class instrumentation support and classloader implementations to be used in certain application servers Spring Framework - Core Dmitry Noskov
  • 12. Data Access/Integration  JDBC - provides a JDBC-abstraction layer  ORM - provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate and iBatis  OXM - provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.  JMS – contains features for producing and consuming messages.  Transaction - supports programmatic and declarative transaction management Spring Framework - Core Dmitry Noskov
  • 13. WEB  Spring’s WEB provides basic web-oriented integration features  WEB-Servlet Spring’s model-view-controller (MVC) implentation  WEB-Struts contains the classes for integrating a classic Struts WEB tier within a Spring application  WEB-Portlet provides the MVC implementation to be used in a portlet environment Spring Framework - Core Dmitry Noskov
  • 14. Full-fledged Spring web application Spring Framework - Core Dmitry Noskov
  • 15. Using a third-party web framework Spring Framework - Core Dmitry Noskov
  • 16. Remoting Spring Framework - Core Dmitry Noskov
  • 17. EJB Spring Framework - Core Dmitry Noskov
  • 18. The Spring triangle Spring Framework - Core Dmitry Noskov
  • 19. Spring IoC container IoC pattern Application lifecycle Essence of Spring IoC container Instantiation an ApplicationContext Spring Framework - Core Dmitry Noskov
  • 20. What is IoC?  is a concept in application development  "don’t call me, I’ll call you"  one form is Dependency Injection (DI) Spring Framework - Core Dmitry Noskov
  • 21. Dependency Injection  is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method  exist in two major variants 1) constructor injection 2) setter injection Spring Framework - Core Dmitry Noskov
  • 22. IoC vs DI vs Factory  DI it is specific type of IoC  The Factory pattern’s main concerns is creating  The DI’s main concern is how things are connected together  DI related to Factory and Strategy patterns, but mostly resembles to Build Pattern Spring Framework - Core Dmitry Noskov
  • 23. Application lifecycle Initialization Use Destruction • creating • process • shuts services requests down • allocate • 99% of • release resources the time resources Spring Framework - Core Dmitry Noskov
  • 24. Essence of IoC container Spring Framework - Core Dmitry Noskov
  • 25. Terms  ApplicationContext  represents the Spring IoC container  bean  is an object that managed by Spring IoC container  BeanDefinition  describe a bean instance Spring Framework - Core Dmitry Noskov
  • 26. Context lifecycle Load BFPP Instantiation Property BPP Ready definitions injection to use Spring Framework - Core Dmitry Noskov
  • 27. Bean lifecycle Spring Framework - Core Dmitry Noskov
  • 28. Creating application context  environments  standalone  WEB  JUnit  EJB  special prefixes  classpath  file system  relative path Spring Framework - Core Dmitry Noskov
  • 29. Instantiation for standalone  ClassPathApplicationContext  FileSystemApplicationContext ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"services.xml", "repositories.xml"}); // retrieve configured instance CurrencyService currencyService = context.getBean("currency", CurrencyService.class); AccountService accountService = context.getBean(AccountService.class); Spring Framework - Core Dmitry Noskov
  • 30. Instantiation for WEB applications Servlet 2.4+ Servlet 2.3 <context-param> <servlet> <param-name> contextConfigLocation <servlet-name> </param-name> context <param-value> /WEB-INF/daoContext.xml </servlet-name> /WEB-INF/applicationContext.xml <servlet-class> </param-value> org.springframework.web.context.ContextLoaderServlet </context-param> </servlet-class> <listener> <load-on-startup>1 <listener-class> org.springframework.web.context.ContextLoaderListener </load-on-startup> </listener-class> </servlet> </listener> Spring Framework - Core Dmitry Noskov
  • 31. Bean Scope Simple Runtime WEB CGLIB / JDK proxies Spring Framework - Core Dmitry Noskov
  • 32. Spring Bean Scopes  simple  singleton  prototype  runtime  thread  custom implementation  web-aware scopes (available only for web-aware ApplicationContext)  request  session  global session Spring Framework - Core Dmitry Noskov
  • 33. The singleton scope Spring Framework - Core Dmitry Noskov
  • 34. The prototype scope Spring Framework - Core Dmitry Noskov
  • 35. Custom scope public interface org.springframework.beans.factory.config.Scope { //Return the object with the given name from the underlying scope Object get(String name, ObjectFactory<?> objectFactory); //Remove the object with the given name from the underlying scope. Object remove(String name); //Register a callback to be executed on destruction of the specified object void registerDestructionCallback(String name, Runnable callback); //Resolve the contextual object for the given key, if any. Object resolveContextualObject(String key); //Return the conversation ID for the current underlying scope, if any. String getConversationId(); } Spring Framework - Core Dmitry Noskov
  • 36. Using runtime scope <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer"> <property name="scopes"> <map> <entry key="thread"> <bean class="org.springframework.context.support.SimpleThreadScope"/> </entry> </map> </property> </bean> <bean id="threadService" class="example.ThreadServiceImpl" scope="thread"> <property name="priority" value="0"/> <aop:scoped-proxy/> </bean> <bean id="threadMonitor" class="example.ThreadMonitorImpl"> <property name="threadService" ref="thredService"/> </bean> Spring Framework - Core Dmitry Noskov
  • 37. Scoped bean as dependencies Using CGLIB library (by default) <bean id="preferences" class="UserPreferences" scope="session"> <aop:scoped-proxy/> </bean> <bean id="userManager" class="example.UserManager"> <property name="userPreferences" ref="preferences"/> </bean> Using JDK interface based proxies means <bean id="preferences" class="UserPreferences" scope="session"> <aop:scoped-proxy proxy-target-class="false"/> </bean> <bean id="userManager" class="example.UserManager"> <property name="userPreferences" ref="preferences"/> </bean> Spring Framework - Core Dmitry Noskov
  • 38. WEB-aware scope configuration Servlet 2.4+ Servlet 2.3 <web-app> <web-app> <listener> <filter> <filter-name>filter</filter-name> <listener-class> <filter-class> org.springframework.web.context.request. RequestContextListener …web.filter.RequestContextFilter </listener-class> </filter-class> </listener> </filter> </web-app> <filter-mapping> <filter-name>filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Spring Framework - Core Dmitry Noskov
  • 39. XML-based configuration Configuration Main features Bean lifecycle Additional features Spring Framework - Core Dmitry Noskov
  • 40. Namespaces <?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="" class=""></bean> <bean id="" class=""/> </beans> Spring Framework - Core Dmitry Noskov
  • 41. BeanFactoryPostProcessor public interface BeanFactoryPostProcessor { /** * Modify the application context's internal bean factory after its standard * initialization. All bean definitions will have been loaded, but no beans * will have been instantiated yet. This allows for overriding or adding * properties even to eager-initializing beans. * @param beanFactory the bean factory used by the application context * @throws org.springframework.beans.BeansException in case of errors */ void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory); } Spring Framework - Core Dmitry Noskov
  • 42. Instantiating bean Spring Framework - Core Dmitry Noskov
  • 43. Naming beans <beans> <bean id="beanId" class="org.exhanger.api.OrderServiceImpl"/> <bean name="name/" class="org.exhanger.api.OrderServiceImpl"/> <bean name="name1,name2;name3 name4" class="..."> </bean> <alias name="fromName" alias="toName"/> </beans> Spring Framework - Core Dmitry Noskov
  • 44. Instantiating bean  with a constructor  with a static factory method  using an instance factory method  with the FactoryBean Spring Framework - Core Dmitry Noskov
  • 45. Instantiating with a constructor  simple class <bean id="exampleBean" class="examples.ExampleBean"/> public class ExampleBean { public ExampleBean() {} }  inner class <bean id="innerBean" class="examples.ExampleBean$InnerBean"/> public class ExampleBean { public static class InnerBean { } } Spring Framework - Core Dmitry Noskov
  • 46. Instantiating with a static method <bean id="clientService" class="examples.ClientService" factory-method="createInstance"/> public class ClientService { private static ClientService clientService = new ClientService(); private ClientService() {} public static ClientService createInstance() { return clientService; } } Spring Framework - Core Dmitry Noskov
  • 47. Using an instance factory method <!-- the factory bean--> <bean id="serviceLocator" class="example.ServiceLocator"/> <!-- the bean to be created via the factory bean --> <bean id="clientService" factory-bean="serviceLocator" factory-method="createClientServiceInstance"/> public class ServiceLocator { private static ClientService clientService = new ClientService(); public ClientService createClientServiceInstance() { return clientService; } } Spring Framework - Core Dmitry Noskov
  • 48. Instantiating with the FactoryBean public interface FactoryBean<T> { /**Return an instance of the object managed by this factory.*/ T getObject() throws Exception; /** Return the type of object that this FactoryBean creates.*/ Class<?> getObjectType(); /**Is the object managed by this factory a singleton? */ boolean isSingleton(); } <bean id="bean" class="FactoryBean"/> Spring Framework - Core Dmitry Noskov
  • 49. Dependency injection Spring Framework - Core Dmitry Noskov
  • 50. Constructor-based DI  is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency  calling a static factory method with specific arguments to construct the bean is nearly equivalent Spring Framework - Core Dmitry Noskov
  • 51. Constructor argument resolution  argument resolution <bean id="b1" class="org.examples.ClientServiceBean"> <constructor-arg ref="b2"/> <constructor-arg ref="b3"/> </bean>  argument type matching <bean id="b2" class="ClientService" factory-method="getInstance"> <constructor-arg type="int" value="7500000"/> <constructor-arg type="java.lang.String" value="42"/> </bean>  argument index <bean id="b3" factory-bean="factory" factory-method="getInstance"/> <constructor-arg index="0" value="75"/> <constructor-arg index="1" value="42"/> </bean> Spring Framework - Core Dmitry Noskov
  • 52. Setter-based DI  is accomplished by the container calling setter methods on your beans after invoking a no- argument constructor or no-argument static factory method to instantiate bean Spring Framework - Core Dmitry Noskov
  • 53. Constructor vs setter  constructor  mandatory dependencies  immutability  setter  optional dependencies and default values  obvious names  auto inheritance Spring Framework - Core Dmitry Noskov
  • 54. Straight values <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" > <!-- results in a setDriverClassName(String) call --> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url"> <value>jdbc:mysql://localhost:3306/mydb</value> </property> <property name="username" value="root"/> <property name="password" value="masterkaoli"/> </bean> Spring Framework - Core Dmitry Noskov
  • 55. Null and empty values <!-- is equivalent to the following code: bean.setEmail("").--> <bean class="Bean"> <property name="email" value=""/> </bean> <!-- The <null/> element handles null values. --> <bean class="Bean"> <property name="email"><null/></property> </bean> Spring Framework - Core Dmitry Noskov
  • 56. properties <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:jdbc.properties"/> </bean> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClass}"/> <property name="url" > <value>${jdbc.url}</value> </property> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> Spring Framework - Core Dmitry Noskov
  • 57. idref bean <bean id="theTargetBean" class="..."/> <bean id="theClientBean" class="..."> <property name="targetName"> <idref bean="theTargetBean" /> </property> </bean> local <property name="targetName"> <!--a bean with id 'theTargetBean' must exist --> <idref local="theTargetBean"/> </property> Spring Framework - Core Dmitry Noskov
  • 58. Reference to other bean  bean <ref bean="someBean"/>  local <ref local="someBean"/>  parent <!-- in the parent context --> <bean id="accountService" class="com.foo.SimpleAccountService"/> <!-- in the child (descendant) context --> <bean id="accountService" class="org.springframework.ProxyFactoryBean"> <property name="target"> <ref parent="accountService"/> </property> </bean> Spring Framework - Core Dmitry Noskov
  • 59. Inner bean <bean id="orderService" class="OrderServiceImpl"> <property name="repository" ref="orderRepository"/> <property name="builder"> <bean class="OrderBuilderImpl"> <constructor-arg ref="accountService"/> <constructor-arg ref="currencyService"/> </bean> </property> </bean> Spring Framework - Core Dmitry Noskov
  • 60. Collections(1) <!-- setAdminEmails(java.util.Properties) call --> <property name="adminEmails"> <props> <prop key="administrator">administrator@gmail.com</prop> </props> </property> <!-- setSomeList(java.util.List) call --> <property name="someList"> <list> <value>a list element followed by a reference</value> <ref bean="myDataSource" /> </list> </property> Spring Framework - Core Dmitry Noskov
  • 61. Collections(2) <!-- setSomeMap(java.util.Map) call --> <property name="someMap"> <map> <entry key="an entry" value="just some string"/> <entry key ="a ref" value-ref="myDataSource"/> </map> </property> <!-- setSomeSet(java.util.Set) call --> <property name="someSet"> <set> <value>just some string</value> <ref bean="myDataSource" /> </set> </property> Spring Framework - Core Dmitry Noskov
  • 62. p namespace <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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="orderService" class="OrderServiceImpl" p:repository-ref="orderRepository" p:locaton="BY"/> </beans> Spring Framework - Core Dmitry Noskov
  • 63. util namespace <?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:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> </beans> Spring Framework - Core Dmitry Noskov
  • 64. util in action <property name="isolation"> <util:constant static-field="java.sql.Connection.TRANSACTION_SERIALIZABLE"/> </property> <bean id="testBean" class="org.springframework.beans.TestBean"> <property name="age" value="10"/> </bean> <util:property-path id="name" path="testBean.age"/> <util:properties id="" location="classpath:jdbc.properties"/> <util:list id="emails" list-class=""><value/><value/></util:list> <util:map id="emails" map-class=""><entry key="" value=""/></util:map> <util:set id="emails" set-class=""><value></value></util:set> Spring Framework - Core Dmitry Noskov
  • 65. Additional features  bean definition inheritance  importing configuration files  autowiring  lazy initialization  dependency checking Spring Framework - Core Dmitry Noskov
  • 66. Bean definition inheritance <!—attribute class is optional  <bean id="parent" abstract="true" class="AbstractService"> <property name="name" value="parent"/> <property name="age" value="1"/> </bean> <bean id="service" class="ServiceImpl" parent="parent"> <property name="name" value="override it"/> </bean> Spring Framework - Core Dmitry Noskov
  • 67. Bean definition inheritance(2) <bean id="parent" abstract="true"> <property name="name" value="parent"/> </bean> <bean id="default" class="DefaultServiceImpl" parent="parent"> <property name="name" value="default"/> <property name="value" value="22"/> </bean> <bean id="custom" class="CustomServiceImpl" parent="default"> <property name="name" value="custom"/> </bean> Spring Framework - Core Dmitry Noskov
  • 68. Importing configuration files  xml-context-config.xml <beans> <import resource="classpath:xml-repository-config.xml"/> <import resource="classpath:xml-service-config.xml"/> </beans>  xml-service-config.xml <beans> <bean id="currencyRepository" class="CurrencyMapRepository"/> </beans>  xml-repository-config.xml <bean id="currencyService" class="CurrencyServiceImpl"> <constructor-arg ref="currencyRepository"/> </bean> Spring Framework - Core Dmitry Noskov
  • 69. Using depends-on  can explicitly force one or more beans to be initialized before the bean using this element is initialized <bean id="beanOne" class="ExampleBean" depends-on="costService,accountDao"> <property name="deviceManager" ref="deviceManager" /> </bean> <bean id="costService" class="example.service.CostService" /> <bean id="accountDao" class="example.jdbc.JdbcAccountDao" /> Spring Framework - Core Dmitry Noskov
  • 70. Lazy-initialized beans  IoC container create a bean instance when it is first requested <bean id="lazy" class="ExpensiveToCreateBean" lazy-init="true"/>  control lazy-initialization at the container level <beans default-lazy-init="true"> <!-- no beans will be pre-instantiated... --> </beans>  disadvantages  errors in the configuration or surrounding  environment are detected some time later Spring Framework - Core Dmitry Noskov
  • 71. Autowiring  advantages  can significantly reduce the need to specify properties or constructor arguments  can update a configuration as your objects evolve  disadvantages  cannot autowire simple properties (primitives)  autowiring is less exact than explicit wiring  wiring information may not be available to tools that may generate documentation from a Spring container Spring Framework - Core Dmitry Noskov
  • 72. Autowiring modes  no (default)  byName <bean id="messageSource" class="MessageSourceImpl" /> public void setMessageSource(MessageSource messageSource)  byType <bean id="messageSource" class="MessageSourceImpl" /> public void setMessageSource(MessageSource messageSource)  constructor  autodetect Spring Framework - Core Dmitry Noskov
  • 73. Dependency checking  none (default)  simple checking for primitive types and collections  object checking for collaborators only  all Spring Framework - Core Dmitry Noskov
  • 74. Spring Aware Interfaces Spring Framework - Core Dmitry Noskov
  • 75. Spring aware interfaces  BeanNameAware  BeanFactoryAware  ApplicationContextAware  ApplicationEventPublisherAware  ServletConfigAware  ServletContextAware  MessageSourceAware Spring Framework - Core Dmitry Noskov
  • 76. Application events public class SomeService implements ApplicationContextAware { public void setApplicationContext(ApplicationContext ctx) {} public void anyMethod(String value) { context.publishEvent(new AnyEvent(value)); } } public class Listener implements ApplicationListener<AnyEvent> { public void onApplicationEvent(AnyEvent event) { } } Spring Framework - Core Dmitry Noskov
  • 77. Internationalization <bean class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list><value>label</value><value>exceptions</value></list> </property> </bean> public interface MessageSource { /** Try to resolve the message. Return default if no message was found.*/ String getMessage(String code, Object[] args, String default, Locale locale); /** Try to resolve the message. Treat an error if the message can't be found.*/ String getMessage(String code, Object[] args, Locale locale); /** Try to resolve the message using MessageSourceResolvable */ String getMessage(MessageSourceResolvable resorvable, Locale locale); } Spring Framework - Core Dmitry Noskov
  • 78. Initialization Spring Framework - Core Dmitry Noskov
  • 79. BeanPostProcessor /** * ApplicationContexts can autodetect BeanPostProcessor beans in their * bean definitions and apply them to any beans subsequently created. */ public interface BeanPostProcessor { /** * Apply this BeanPostProcessor to the given new bean instance before any bean * initialization callbacks (like afterPropertiesSet or a custom init-method)*/ Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; /** * Apply this BeanPostProcessor to the given new bean instance after any bean * initialization callbacks (like afterPropertiesSet or a custom init-method). */ Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; } Spring Framework - Core Dmitry Noskov
  • 80. Initialization callbacks <bean id="bean1" class="exampl.ExampleBean1" init-method="init"/> public class ExampleBean1 { public void init() {} } <bean id="bean2" class="examples.ExampleBean2"/> public class ExampleBean2 implements InitializingBean { public void afterPropertiesSet() {} } public class ExampleBean2 { @PostConstruct public void initialize() {} } Spring Framework - Core Dmitry Noskov
  • 81. Destroy Spring Beans Spring Framework - Core Dmitry Noskov
  • 82. Destruction callbacks <bean id="bean1" class="example.Bean1" destroy-method="cleanup"/> public class Bean1 { public void cleanup() {} } <bean id="bean2" class="example.Bean2"/> public class Bean2 implements DisposableBean { public void destroy() {} } public class Bean2 { @PreDestroy public void destroy() {} } Spring Framework - Core Dmitry Noskov
  • 83. Combining lifecycle mechanisms  initialization methods, are called as follows:  methods annotated with @PostConstruct  afterPropertiesSet as defined by InitializingBean  custom configured init method  destroy methods are called in the same order:  method annotated with @PreDestroy  destroy() as defined by the DisposableBean  custom configured destroy method Spring Framework - Core Dmitry Noskov
  • 84. Annotation-based configuration Basic annotations Spring stereotypes JSR-250 JSR-330 Spring Framework - Core Dmitry Noskov
  • 85. Annotation based configuration  an alternative to XML setups  annotation injections is performed before XML Spring Framework - Core Dmitry Noskov
  • 86. Basic annotations(1)  Spring Annotations  @Autowired  @Qualifier  @Required  @Value  JSR 250  @Resource  @PostConstruct  @PreDestroy Spring Framework - Core Dmitry Noskov
  • 87. Basic annotations(2)  context  @Scope  @Bean  @DependsOn  @Lazy  transactional  @Transactional Spring Framework - Core Dmitry Noskov
  • 88. Stereotypical @Component Any component @Repository @Service @Controller @Configuration Data access Service classes Spring MVC Java Config Spring Framework - Core Dmitry Noskov
  • 89. Basic configuration <!-- looks for annotations on beans --> <context:annotation-config/> <!– scan stereotyped classes and register BeanDefinition --> <context:component-scan base-package="org.exhanger.repository.map,org.exhanger.api"> Spring Framework - Core Dmitry Noskov
  • 90. Basic configuration(2) <context:component-scan base-package="org.exhanger" name-generator="my.NameGeneratorImpl" resource-pattern="**/*.class" scope-resolver="my.ScopeResolverImpl" scoped-proxy="no|interfaces|targetClass"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> <context:exclude-filter type="regex" expression=".*MapRepository"/> </context:component-scan> Spring Framework - Core Dmitry Noskov
  • 91. @Value @Component("authenticationProvider") public class EjbAuthenticationProvider { /** The provider api connection url. */ @Value("${provider.api.url}") private String apiUrl; /** The provider api connection username. */ private @Value("${provider.api.username}") String apiUsername; /** The provider api connection password. */ @Value("${provider.api.password}") private String apiPassword; } Spring Framework - Core Dmitry Noskov
  • 92. @Autowired(1) @Service("accountService") public class AccountServiceImpl { @Autowired private AccountRepository repository; @Autowired public AccountServiceImpl(AccountRepository repository) {} @Autowired(required = false) public void setRepository(AccountRepository repository) {} @Autowired public void populate(Repository r, OrderService s) {} } Spring Framework - Core Dmitry Noskov
  • 93. @Autowired(2) @Service public class AccountServiceImpl { @Autowired private AccountRepository[] repositories; @Autowired public AccountServiceImpl(Set<AccountRepository> set) {} @Autowired(required = false) public void setRepositories(Map<String,AccountRepository> map){ } } Spring Framework - Core Dmitry Noskov
  • 94. @Required(1) public class AccountServiceImpl { private AccountRepository repository; @Required public void setRepository(AccountRepository repository) {} } <bean name="accountService" class="AccountServiceImpl"> <property name="repository" ref="accountRepository"/> </bean> Spring Framework - Core Dmitry Noskov
  • 95. @Required(2) public class AccountServiceImpl { private AccountRepository repository; @Mandatory public void setRepository (AccountRepository repository) {} } <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"> <property name="requiredAnnotationType" value="my.Mandatory"/> </bean> @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Mandatory {} Spring Framework - Core Dmitry Noskov
  • 96. @Qualifier public class ReportServiceImpl { @Autowired @Qualifier("main") private DataSource mainDataSource; @Autowired @Qualifier("freeDS") private DataSource freeDataSource; } <beans> <bean class="org.apache.commons.dbcp.BasicDataSource"> <qualifier value="main"/> </bean> <bean id="freeDS" class="org.apache.commons.dbcp.BasicDataSource"/> </beans> Spring Framework - Core Dmitry Noskov
  • 97. @Resource public class AccountServiceImpl { @Resource(name = "orderService") private OrderService orderService; @Resource(name = "orderService") public void setOrderService(OrderService orderService) {} @Resource private AuditService auditService; @Resource public void setAuditService(AuditService auditService) {} } Spring Framework - Core Dmitry Noskov
  • 98. @Scope @Service @Scope("prototype") public class AccountServiceImpl implements AccountService { } @Service @Scope(value = BeanDefinition.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS) public class AccountServiceImpl implements AccountService { } Spring Framework - Core Dmitry Noskov
  • 99. @Lazy & @DependsOn @Lazy @Service @DependsOn({"orderService", "currencyService"}) public class AccountServiceImpl implements AccountService { } Spring Framework - Core Dmitry Noskov
  • 100. Factory method component @Component public class CurrencyRepositoryFactory { @Bean @Lazy @Scope("prototype") @Qualifier("public") public CurrencyRepository getCurrencyRepository() { return new CurrencyMapRepository(); } } Spring Framework - Core Dmitry Noskov
  • 101. JSR 330 @Named @Singleton public class AccountServiceImpl implements AccountService { @Inject private AccountRepository repository; @Inject public AccountServiceImpl(@Named("default") AccountRepository r) {} @Inject public void setAccountRepository(AccountRepository repository) {} } Spring Framework - Core Dmitry Noskov
  • 102. @Autowired vs @Inject Spring JSR-330 JSR-330 restrictions @Autowired @Inject has no ‘required’ attribute @Component @Named @Scope @Scope only for meta-annotations and injection points @Scope @Singleton default scope is like ‘prototype’ @Qualifier @Named @Value X @Required X @Lazy X Spring Framework - Core Dmitry Noskov
  • 103. Java-based configuration Configuration Basic annotations Spring Framework - Core Dmitry Noskov
  • 104. Instantiatiating for standalone  simple new AnnotationConfigApplicationContext(ExchangerConfig.class);  programmaticaly context = new AnnotationConfigApplicationContext(); context.register(ExchangerConfig.class); context.refresh();  scanning context = new AnnotationConfigApplicationContext(); context.scan("org.exchanger.config"); context.refresh(); Spring Framework - Core Dmitry Noskov
  • 105. Instantiating bean @Configuration public class ExchangerRepositoryConfg { @Bean(name = "accountRepository", initMethod = "init") public AccountRepository accountRepository() { return new AccountMapRepository(); } @Bean public AuditRepository auditRepository() { return new AuditMapRepository(); } } Spring Framework - Core Dmitry Noskov
  • 106. @Import @Configuration @Import({RepositoryConfig.class, ServiceConfig.class}) public class ExchangerConfig { } @Configuration public class RepositoryConfg {} @Configuration public class ServiceConfig {} Spring Framework - Core Dmitry Noskov
  • 107. @ImportResources @Configuration @ImportResource("classpath:jdbc.properties") public class ExchangerConfig { @Value("jdbc.url") private String jdbcUrl; @Bean public DataSourse dataSource() { return new SimpleDataSource(jdbcUrl); } } Spring Framework - Core Dmitry Noskov
  • 108. Dependency injection @Configuration public class ExchangerServiceConfig { @Autowired private CurrencyRepository currencyRepository; public @Bean CurrencyService currencyService() { return new CurrencyServiceImpl(currencyRepository); } @Bean(name = {"orderBuilder", "builder"}) public OrderBuilder orderBuilder() { return new OrderBuilder(currencyService(), accountService()); } } Spring Framework - Core Dmitry Noskov
  • 109. Summary Benefits of IoC Context lifecycle Mix and match Spring Framework - Core Dmitry Noskov
  • 110. Benefits of IoC  minimizes the amount of code  make application more testable  promote programming to interfaces  loose coupling with minimal effort  support eager instantiation and lazy loading  provide control over object lifecycle Spring Framework - Core Dmitry Noskov
  • 111. Context lifecycle Spring Framework - Core Dmitry Noskov
  • 112. Approach to configuration  XML  infrastructure beans  annotations  working beans  java  an alternative to the FactoryBean Spring Framework - Core Dmitry Noskov
  • 113. You can mix and match  dependency injection  constructor-based and setter-based  you can mix and match  configuration metadata  XML, annotations, Java  you can mix and match  annotations  own, JSR-250, JSR-330  you can mix and match Spring Framework - Core Dmitry Noskov
  • 114. Links  site http://www.springsource.org/  reference http://static.springsource.org/spring/docs/3.0.x/spring- framework-reference/html/  blog http://blog.springsource.com/category/spring/  forum http://forum.springsource.org/forumdisplay.php?f=26 Spring Framework - Core Dmitry Noskov
  • 115. Books Spring Framework - Core Dmitry Noskov
  • 116. Questions Spring Framework - Core Dmitry Noskov
  • 117. The end http://www.linkedin.com/in/noskovd http://www.slideshare.net/analizator/presentations