Blog Image

What is depends on with example.  

Here we are going to explore about spring provided Depends On to know how we can work with depends on in our projects.

If a class uses the functionality of other class inside it, then those classes are directly dependent on each other. But in some cases some classes are not directly dependent on each other, there may be indirect dependency.
So, in such cases we have to tell to the IOC container to create the bean of dependent class, before creating the bean of our class. To tell this to IOC container spring has provided "depends-on" attribute.
Using this attribute we can tell to the IOC container which beans to be created first before creating current bean.

Below example shows how to use depends-on attribute in spring.

Lets see the example:
Technologies used :-
1) java (1.8).
2) maven (3.5.2).
3) Spring (3.0.0).

Project Structure

Execute below command for creating maven project.
mvn archetype:generate -DgroupId=com.sjg
-DartifactId=example-on-depends-on
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false

Below is the maven project structure with packages and java src files.

Classes
CityRiPropsFileAccessor.java
package com.sjg.accessor;

import java.io.IOException;
import java.util.Properties;

public class CityRiPropsFileAccessor implements IAccessor {
    private String key;

    public Object getData() {
        Properties props = null;

        props = new Properties();
        try {
            props.load(this.getClass().getClassLoader().getResourceAsStream("city-ri.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return props;

    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;

    }

}
IAccessor.java
package com.sjg.accessor;

public interface IAccessor {
    Object getData();

    String getKey();

    void setKey(String key);

}
LoanCalculator.java
package com.sjg.beans;

import java.util.Properties;
import com.sjg.util.Cache;

public class LoanCalculator {
    private final String KEY_CITY_RI = "CITY_RI";
    private Cache cache;

    public float calculate(long principle, int tenure, String city) throws Exception {
        float ri = 0.0f;
        float intAmount = 0.0f;
        Properties props = null;

        if (cache.containsKey(KEY_CITY_RI) == false) {
            throw new Exception("Cache not initialized!");
        }

        props = (Properties) cache.get(KEY_CITY_RI);
        if (props.containsKey(city) == false) {
            throw new Exception("City Not found");
        }

        ri = Float.parseFloat(props.getProperty(city));
        intAmount = (principle * tenure * ri) / 100;

        return intAmount;
    }

    public void setCache(Cache cache) {
        this.cache = cache;
    }

}
application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans";
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">;

    <bean id="cityRiPropsFileAccessor" class="com.sjg.accessor.CityRiPropsFileAccessor">
        <property name="key" value="CITY_RI" />
    </bean>
    <bean id="cache" class="com.sjg.util.Cache" factory-method="getInstance" />
    <bean id="cacheManager" class="com.sjg.util.CacheManager">
        <constructor-arg ref="cache" />
        <constructor-arg>

            <ref bean="cityRiPropsFileAccessor" />

        </constructor-arg>
    </bean>
    <bean id="loanCalculator" class="com.sjg.beans.LoanCalculator"
        depends-on="cacheManager">
        <property name="cache" ref="cache" />
    </bean>
</beans>
Cache.java
package com.sjg.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Cache {
    private static Cache instance;
    private Map<String, Object> dataMap;

    private Cache() {
        dataMap = new ConcurrentHashMap<String, Object>();
    }

    public static synchronized Cache getInstance() {
        if (instance == null) {
            instance = new Cache();
        }
        return instance;
    }

    public void put(String key, Object val) {
        dataMap.put(key, val);
    }

    public Object get(String key) {
        return dataMap.get(key);
    }

    public boolean containsKey(String key) {
        return dataMap.containsKey(key);

    }

}
CacheManager.java
package com.sjg.util;

import java.util.List;
import com.sjg.accessor.IAccessor;

public class CacheManager {
    private Cache cache;
    private List<IAccessor> accessors;

    public CacheManager(Cache cache, List<IAccessor> accessors) {
        this.cache = cache;
        this.accessors = accessors;
        init();
    }

    public void init() {
        String key = null;
        Object val = null;

        for (IAccessor accessor : accessors) {
            key = accessor.getKey();
            val = accessor.getData();
            cache.put(key, val);

        }

    }

}
city-ri.properties
HYD=12.12
BLR=11.23
CHN=12.32
pom.xml
package com.sjg.test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.sjg.beans.LoanCalculator;

public class Test {
    public static void main(String[] args) throws Exception {
        BeanFactory factory = new XmlBeanFactory(new ClassPathResource("com/sjg/common/application-context.xml"));
        LoanCalculator lc = factory.getBean("loanCalculator", LoanCalculator.class);
        float amt = lc.calculate(100, 10, "HYD");
        System.out.println("Interest : " + amt);

    }

}

Please find attached the example_on_depends_on.zip as an maven project as a reference. Feel free to pass your comments in the blog.


About author

User Image
Sriman

A software developer on JDK and JEE platform. I am passionate about Java technology and always an explorer and learner in new technologies in Java. I have experience on Open Source technologies like Struts, Spring, Jsf etc.. and even strong knowledge on Integration/Distributed world like Ejb, Web Services and Restful Services.

0

-Comments

Be the first person to write a comment for this Blog
Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.