Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create spring bean with collection data decoupled from parent bean?

Spring has ability to initialisate values of core java collection types.

I have a complex collection type Map<String, Set<String>> map and it inital value defined in spring config:

<bean id="dao" class="ru.mypkg.dao.DaoImpl">
    <property name="dataSource" ref="dataSource"/>
    <property name="map">
        <map>
            <entry key="TABLE">
                <set>
                    <value>COMMENT</value>
                    <value>INDEX</value>
                </set>
            </entry>
            <entry key="VIEW">
                <set>
                    <value>COMMENT</value>
                </set>
            </entry>
        </map>
    </property>
</bean>

I want rewrite my config in next manner: Split it on 2 beans for more readability

<bean id="dao" class="ru.mypkg.dao.DaoImpl">
    <property name="dataSource" ref="dataSource"/>
    <property name="map" ref-id="myMap"/>        
</bean>

<bean id="myMap" ..????..>
        <entry key="TABLE">
                <set>
                    <value>COMMENT</value>
                    <value>INDEX</value>
                </set>
            </entry>
            <entry key="VIEW">
                <set>
                    <value>COMMENT</value>
                </set>

            </entry>
</bean>

Can I achieve that with no creating additional classes?

like image 711
qwazer Avatar asked Feb 20 '11 11:02

qwazer


People also ask

What will happen if there are two beans with the same ID?

Here, @Bean instantiates two beans with ids the same as the method names and registers them within the BeanFactory (Spring container) interface. Next, we can initialize the Spring container and request any of the beans from the Spring container. This strategy also makes it simple to achieve dependency injection.

Is bean factory responsible for managing beans and their dependencies?

BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container interface in Spring.

How do I remove a spring context from a bean?

A spring bean can be removed from context by removing its bean definition. BeanDefinitionRegistry factory = (BeanDefinitionRegistry) context. getAutowireCapableBeanFactory(); factory. removeBeanDefinition("mongoRepository");


1 Answers

Certainly, using the <util:map> namespace. See the Spring documentation C.2.2.5.

Another way to create complex configuration is using the @Configuration approach, or alternatively the FactoryBean interface.

like image 105
Johan Sjöberg Avatar answered Oct 14 '22 09:10

Johan Sjöberg