четверг, 20 ноября 2008 г.

Placeholder trick in Spring

Hello everyone! In the Spring Framework (I use Spring 2.5), we can use property placeholders in the spring xml-based configuration file. I wrote simple example that consist of four beans. Two of them are simple beans, one is a factory and one is a result bean that we want to get from factory bean.


<?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-2.0.xsd">

    <bean id=”simpleFactory” class=”c om.blogger.dooman87.SimpleFactory”>
        <constructor-arg value=”$ {com.blogger.dooman87.resultBeanName}”>
    </bean>

    <bean id="resultBean" factory-bean=”s impleFactory”/>

    <bean id="simpleBeanFirst"
        class="com.blogger.dooman87.SimpleBeanFirst"/>

    <bean id="simpleBeanSecond"
        class="com.blogger.dooman87.SimpleBeanSecond"/>
</beans>


In this case, we should write additional class com.blogger.dooman87.SimpleFactory, that would instantiate result by first constructor argument. This class we can extend from AbstractFactoryBean. But as well we are able to replace the factory! This simple trick you can see below:


<?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-2.0.xsd">

    <alias name="${com.blogger.dooman87.resultBeanName}" alias="resultBean"/>

    <bean id="simpleBeanFirst"
        class="com.blogger.dooman87.SimpleBeanFirst"/>

    <bean id="simpleBeanSecond"
        class="com.blogger.dooman87.SimpleBeanSecond"/>
</beans>


We created alias for result bean, where the name is a placeholder value. That's all. Hope this post was interesting or you.

2 комментария:

சின்னப்பயல் комментирует...

Hello, a short while ago I was looking out for a Java Interview Questions, a renewed path, and I found this awesome site, http://www.prepareinterview.com/tips/questionJavaFAQ.asp . They have some brilliant tips, and some interesting links additionally. In less than five weeks I got myself a job. I won't tell you what it is, but I do it at home and I like it!

dimka комментирует...

Hello! Thank you for interesting link. Why you won't tell about your job? I think that it's interesting for me, brcause now I want to change my job.

Most popular

Authors