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="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    
    <bean id="contextSource" class="org.springframework.ldap.core.support.DirContextSource">
        <property name="url" value="ldap://127.0.0.1:7001">
        </property>
        <property name="userDn" value="cn=Admin"> 
        </property>
        <property name="password" value="adminpass0">
        </property>
        <property name="base" value="ou=myrealm,dc=base_domain">
        </property>
    </bean>
 
    <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
        <constructor-arg ref="contextSource" />
    </bean>
    
</beans>



then i wrote a service class that had the producer method


@ApplicationScoped
public class ProducerServices {
     
        @Produces
        @ApplicationScoped
        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

@Named
public class PersonDaoImpl implements PersonDao{
    @Inject
    private LdapTemplate ldapTemplate;
//other stuff
}

No comments:

Post a Comment