SpringLDAP Quick Start

1:前言
本例只在spring-ldap-1.2-RC1.jar下测试通过,sping下的LDAP配置和操作,都类似于JdbcTemplate,所以只要熟悉JdbcTemplate,那么LDAP的配置就显得非常简单。LDAP本身不提供事务,但是Spring使用删除操作来模仿事务。

2:配置LDAP数据源和LdapTemplate
<bean id="ldapSource"
		class="org.springframework.ldap.core.support.LdapContextSource">
		<property name="url" value="ldap://192.168.16.79:10000" />
		<property name="base" value="dc=somc,dc=com" />
		<property name="userDn" value="cn=admin" />
		<property name="password" value="19820914" />
	</bean>

	<bean id="ldapTemplate"
		class="org.springframework.ldap.core.LdapTemplate">
		<constructor-arg ref="ldapSource" />
	</bean>
	<bean id="userDaoLdapImpl" class="UserDaoLdapImpl" />



3:查询代码


import javax.naming.directory.Attributes;

import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.transaction.compensating.manager.ContextSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 
 * 
 * @author kiral
 * @date 2008-12-16
 */
public class UserDaoLdapImpl {

	private LdapTemplate ldapTemplate;

	private ContextSourceTransactionManager transactionManager;

	public void setTransactionManager(ContextSourceTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	public void setLdapTemplate(LdapTemplate ldapTemplate) {
		this.ldapTemplate = ldapTemplate;
	}

	public Person getPersonByDn(String dn) {
		
		new TransactionTemplate(transactionManager)
		.execute(new TransactionCallbackWithoutResult() {

			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		return (Person) ldapTemplate.lookup(dn, new PersonAttributesMapper());
	}

	private class PersonAttributesMapper implements AttributesMapper {

		public Object mapFromAttributes(Attributes attrs)
				throws javax.naming.NamingException {
			Person person = new Person();
			person.setUserCode((String) attrs.get("userCode").get());
			return person;
		}

	}

}


4:测试代码
import com.ultrapower.somc.managerdashboard.test.DaoTestCase;

public class UserDaoLdapImplTest extends DaoTestCase {

	private UserDaoLdapImpl userDaoLdapImpl;

	public void setUserDaoLdapImpl(UserDaoLdapImpl userDaoLdapImpl) {
		this.userDaoLdapImpl = userDaoLdapImpl;
	}

	public void testAll() {
		String dn = "userCode=user001,ou=somcUser";
		String userCode = "user001";
		Person person = userDaoLdapImpl.getPersonByDn(dn);
		assertTrue(userCode.equals(person.getUserCode()));
	}
}

你可能感兴趣的:(spring,xml)