Skip to content

SR Chapter 4

April 19, 2010
tags:

Can use a combination of property and constructor-arg while declaring the bean.

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
<bean id="cdrw" class="com.Disc">
        <constructor-arg value="CD-RW" />
       <property name="capacity" value="700" />
</bean>

Scope of beans
Default: Singleton
Other scopes : prototype (created new each time) , request, session or globalsession(portal app’s)
older version singleton=”true” or singleton=”false”[proto] (only 2 scopes)

A GoF Singleton hardcodes the scope of an object such that one and only one instance of a particular class will ever be created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container will create one and only one instance of the class defined by that bean definition.

If singleton has inject of prototype then only ONCE the prototype is injected in it. That exact same prototype instance will be the sole instance that is ever supplied to the singleton-scoped bean

If you want to insert new prototype object every time in the singleton scope – then use the manual BeanFactoryAware lookup, OR , method injection ( / CGLIB method lookup), OR Method replacement.

Similar problem exists when using Singleton and request or session scoped objects, since Singleton only keeps ONE instance irrespective of the scope of the referencing object – by DEFAULT. So instead of keeping your own dummy object that fetches new data based on session – Use the Spring Proxy object that fetches real data based on scope when calls are received from the singletons.

aop:scoped-proxy tag is required. for the request,session, global scopes.

Life cycle of your beans

Perform initialization and destruction tasks in the callback methods afterPropertiesSet() and destroy() by implementing the InitializingBean and DisposableBean interfaces. And in the configuration file add the tags init-method=”openFile” destroy-method=”closeFile”
OR you can do the @PostConstruct and @PreDestroy annotations on method. and in the configuration xmlns:context=”http://www.springframework.org/schema/context&#8221; ( etc…. ) and tag needed
context:annotation-config

As of Spring 2.5, there are three options for controlling bean lifecycle behavior: the InitializingBean and DisposableBean callback interfaces; custom init() and destroy() methods; and the @PostConstruct and @PreDestroy annotations.
When combining different lifecycle mechanisms – for example, in a class hierarchy in which various lifecycle mechanisms are in use – developers should be aware of the order in which these mechanisms are applied. The following is the ordering for initialization methods:

  • Methods annotated with @PostConstruct
  • afterPropertiesSet() as defined by the InitializingBean callback interface
  • A custom configured init() method

Destroy methods are called in the same order:

  • Methods annotated with @PreDestroy
  • destroy() as defined by the DisposableBean callback interface
  • A custom configured destroy() method
  • Beans aware of Container
    If the bean that you are declaring in the config file needs to be called with the managers of the Container – then it needs to implement certain **Aware interfaces. Like BeanName, BeanFactory, AppContext, MsgSrc, RscLoader-Aware Interfaces.

    BeanPostProcessor
    It will process all the bean instances in the IoC container one by one, not just a single bean instance.Implement the BeanPostProcessor interface.

    For the bean post processor to distinguish which beans should be checked, you create a marker interface. postProcessBeforeInitialization() and postProcessAfterInitialization() methods must return an instance for the bean being processed. That means you may even replace the original bean instance with a brand-new instance in your bean post processor.

    class Abc impl MarkerInterface
    class Processor impl BPProcessor { ppAInit() { if bean instance of MarkerInterface…} //since all beans are passed. To register a bean post processor in an application context, just declare an instance of it
    in the bean configuration

    Order of multiple bean processors : Implement the Ordered or PriorityOrdered interface, and return their order in the getOrder() method. Lower value returned by this method represents higher priority,
    ================
    Bean Property Initialization ways

    Static Factory method’s name in the factory-method Method arguments by using the constructor-arg . Non static factory methods can also be invoked using factory-bean tag.

    <bean id="aaa" factory-bean="productCreator" factory-method="createProduct">
            <constructor-arg value="aaa" />
    </bean>
    

    Spring specific factory classes also exist: FactoryBean interface and template class, AbstractFactoryBean. Other impl like JndiObjectFactoryBean(jndi), ProxyFactoryBean(aop), LocalSessionFactoryBean(hibernate).
    Populate the bean property from a static value. Use of either the built-in factory bean FieldRetrievingFactoryBean (static field property), or the util:constant tag to use this add the xmlns:util=”http://www.springframework.org/schema/util schema and schema instance reference.

    To Init bean from an object property or a property path, you can make use of either the
    built-in factory bean PropertyPathFactoryBean or the util:property-path tag
    ============================================
    Properties
    Get external properties using PropertyPlaceholderConfigurer. prop name= key value. OR
    context:property-placeholder location=”config.properties” and http://www.springframework.org/schema/context/spring-context-2.5.xsd&#8221;.

    ======================================
    i18n

    Resource bundle. : MessageSource is an interface that defines several methods for resolving messages. The
    ApplicationContext interface extends this interface so that all application contexts are able to resolve text messages. Implementation: ResourceBundleMessageSource. Example:

    <bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
    <value>messages</value>
    </property>
    </bean>
    

    First messages_en_US.properties is searched for, and then if not found the file messages.properties is searched for. Call getMessage on AppContext obj to get i18n specific data given locale.Country_Name.Can specify arguments in the message in brackets {1} {2} etc… and pass the needed params in the getMessage call..

    ==================
    Event handling in Spring

    All event classes extend the ApplicationEvent class. Publish an event by calling an application event publisher’s publishEvent() method. To listen to certain events, it must implement the ApplicationListener interface and handle the events in the onApplicationEvent() method. Spring will notify a listener of all events, so you must filter the events by yourself.
    =================
    Property Editors

    Convert string to expected datatype for setting. String to file, InputStream, URL etc.Standard JavaBeans .
    PropertyEditor instances are used to convert property values expressed as strings to the actual complex type of the property. Spring has already many built in editors – need not do any configuration for these. To create custom you need to write some code/config.

    To modify or convert your values using a “FORMATTER” – that is the purpose of these editors. One way to do that is use the factory-bean property of a bean. A property’s value can be a bean whose attribute can be factory-bean and factory-method.

    One way to convert string to Date:

    <property name="fromDate">
    <bean factory-bean="dateFormat" factory-method="parse">
    <constructor-arg value="2007-09-01" />
    </bean>
    </property>
    

    2 other ways:

    1. Make editor class extend the PropertyEditorSupport override setAsText method and do custom registration.
    2. Use the configuration of CustomEditorConfigurer with the types and editor.

    2nd method:
    Another way to do using property editor named CustomEditorConfigurer that has the property named customEditors – which is a Map. The key of this is our own data type to which we need to convert to and the value is the name of our customEditor which helps us in doing the conversion. (who will do/ what will the new datatype).

    <bean id="customEditorConfigurer" 
        class="org.springframework.beans.factory.config.CustomEditorConfigurer">
      <property name="customEditors">
        <map>
          <entry key="example.ExoticType">
            <bean class="example.ExoticTypeEditor">
              <property name="format" value="upperCase"/>
            </bean>
          </entry>
        </map>
      </property>
    </bean>
    

    To register other custom PropertyEditors use a special bean factory post-processor called CustomEditorConfigurer used along with the ApplicationContext. A constructor-arg can be initialized with a bean. isAssignableFrom in class Clazz – used to check class compatibility.

    A. PropertyEditors are injected into the CustomEditorConfigurer using Map customEditors property.

    B. Each entry represents a single PropertyEditor with the key of the entry being the name of the class for
    which the PropertyEditor is used.

    C. An anonymous bean declaration as the value of the single Map entry. No other bean needs to access this
    bean, so it needs no name and as a result, you can declare it inside of the tag.

    Loading external resources
    Make bean rscLoaderAware and this will inject the resourceLoader in the class. Next declare an init-method in bean declaration. Then in that rscLoader.getResource(“file:banner.txt”); and then class stream after done.

    Resource prefixes: file:c:/shop/banner.txt, classpath:banner.txt OR http://a.com/b.txt

    OR best to use built in property editor named : preregistered property editor ResourceEditor. Just inject Resource object with string value of any resource.

    AppContext has AOP and transaction support over BeanFactory .

    <util:list id="myList" list-class="java.util.Vector">
        <value>valueOne</value>
        <value>valueTwo</value>
    </util:list>
    
    Advertisements
    No comments yet

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s

    %d bloggers like this: