Как автоматически связать LdapRepository весной? - PullRequest
0 голосов
/ 27 октября 2018

Я пытаюсь использовать автоконфигурацию Spring для раскрутки встроенного сервера LDAP и доступа к нему с помощью spring-data-ldap.Однако поля с автосвязью, репозиторий (экземпляр LdapRepository) и ldapTemplate (экземпляр LdapTemplate) имеют нулевое значение.

Например,

spring.ldap.model.UserTest > testSaveUser FAILED
    java.lang.NullPointerException at UserTest.java:32

Что мне не хватает?

build.gradle

plugins {
  id 'org.springframework.boot' version '2.0.6.RELEASE' apply false
}

apply plugin: 'io.spring.dependency-management'
apply plugin: 'java'

repositories {
  jcenter()
}

dependencyManagement {
  imports {
    mavenBom org.springframework.boot.gradle.plugin.SpringBootPlugin.BOM_COORDINATES
  }
}

dependencies {
  compile 'org.springframework.data:spring-data-ldap'
  compile 'com.unboundid:unboundid-ldapsdk'
  testCompile 'org.springframework.boot:spring-boot-starter-data-ldap'
  testCompile 'org.springframework.boot:spring-boot-starter-test'
}

sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

Под src / main / java / spring / ldap / model:

Config.java

пакет spring.ldap.модель;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.ldap.repository.config.EnableLdapRepositories;

@Configuration
@EnableLdapRepositories
public class Config { }

User.java

package spring.ldap.model;

import javax.naming.Name;

import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.DnAttribute;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;

@Entry(objectClasses = { "person", "top" }, base="dc=spring,dc=ldap,dc=model" )
public class User {
  @Id private Name dn;
  @Attribute(name = "cn") @DnAttribute(value = "cn", index = 0) private String userName;
  @Attribute(name = "sn") private String fullName;

  public Name getDn() { return dn; }
  public void setDn(Name dn) { this.dn = dn; }

  public String getUsername() { return userName; }
  public void setUsername(String userName) { this.userName = userName; }

  public String getFullName() { return fullName; }
  public void setFullName(String fullName) { this.fullName = fullName; }
}

UserRepository.java

package spring.ldap.model;

import org.springframework.data.ldap.repository.LdapRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends LdapRepository<User> { }

Под src / test / java / spring / ldap / model:

UserTest.java

package spring.ldap.model;

import static org.junit.Assert.assertNotNull;

import javax.naming.Name;

import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.support.LdapNameBuilder;
import org.springframework.test.context.ContextConfiguration;

@DataLdapTest()
@ContextConfiguration(classes = Config.class)
public class UserTest {
  @Autowired UserRepository repository;
  @Autowired LdapTemplate ldapTemplate;

  @Before
  public void SetUp() {
    LdapNameBuilder builder = LdapNameBuilder.newInstance();
    builder.add("dc", "model");
    builder.add("dc", "ldap");
    builder.add("dc", "spring");
    Name dn = builder.build();
    DirContextAdapter context = new DirContextAdapter(dn);
    context.setAttributeValues("objectclass", new String[] { "top", "domain", "extensibleObject" });
    context.setAttributeValue("dc", "spring");
    ldapTemplate.bind(context);
  }

  @Test public void testSaveUser() {
    User user = new User();
    user.setUsername("ncornish");
    user.setFullName("Nicholas Cornish");

    repository.save(user);

    assertNotNull("Id was not generated!", user.getDn());
  }
}

В разделе src / test / resources:

application.properties

spring.ldap.embedded.base-dn=dc=spring,dc=ldap,dc=model
spring.ldap.embedded.credential.username=uid=admin
spring.ldap.embedded.credential.password=secret

Ответы [ 2 ]

0 голосов
/ 28 октября 2018

Необходимо поместить эти аннотации в контекст тестового класса:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { UserRepository.class, LdapTemplate.class })
@ContextConfiguration(classes = Config.class)
@EnableConfigurationProperties

С уважением.

0 голосов
/ 27 октября 2018

Спасибо, JB Nezit, ваш комментарий

Ваш тест не работает в контексте Spring, так как он не аннотирован @RunWith (SpringRunner.class).Таким образом, ничто никогда не будет автоматически соединяться внутри него.

решает проблему.то есть.добавьте следующее к тестовому классу

@RunWith(SpringRunner.class)
...