Monday, December 3, 2012

Injecting a spring bean using CDI

A few days back i was facing trouble injecting a spring bean using CDI. after a bit of google-ing i found the following solution. all you got to do is add the spring bean definition in  applicationContext.xml . then create a producer method that produces that bean and supplies it to the CDI for injecting where necessary.

for example i needed the following beans to be injected (its the applicationContext.xml file  )

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <bean id="contextSource" class="">
        <property name="url" value="ldap://">
        <property name="userDn" value="cn=Admin"> 
        <property name="password" value="adminpass0">
        <property name="base" value="ou=myrealm,dc=base_domain">
    <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
        <constructor-arg ref="contextSource" />

then i wrote a service class that had the producer method

public class ProducerServices {
        public LdapTemplate getLdapTemplate() {
                return (LdapTemplate) ContextLoader.getCurrentWebApplicationContext().getBean(LdapTemplate.class);

so when I later injected the spring bean in the following class it worked perfectly

public class PersonDaoImpl implements PersonDao{
    private LdapTemplate ldapTemplate;
//other stuff

No comments:

Post a Comment