使用
要訪問儲存在符合 LDAP 目錄中的域實體,您可以使用我們先進的 Repository 支援,它能顯著簡化實現。 為此,請為您的 Repository 建立一個介面,如下例所示
例 1. Person 實體示例
@Entry(objectClasses = { "person", "top" }, base="ou=someOu")
public class Person {
@Id
private Name dn;
@Attribute(name="cn")
@DnAttribute(value="cn", index=1)
private String fullName;
@Attribute(name="firstName")
private String firstName;
// No @Attribute annotation means this is bound to the LDAP attribute
// with the same value
private String firstName;
@DnAttribute(value="ou", index=0)
@Transient
private String company;
@Transient
private String someUnmappedField;
// ...more attributes below
}
我們這裡有一個簡單的域物件。請注意,它有一個型別為 Name
的名為 dn
的屬性。有了這個域物件,我們可以建立一個 Repository,透過定義一個介面來持久化該型別的物件,如下所示
例 2. 用於持久化
Person
實體的基本 Repository 介面public interface PersonRepository extends CrudRepository<Person, Long> {
// additional custom finder methods go here
}
因為我們的域 Repository 繼承了 CrudRepository
,所以它為您提供了 CRUD 操作以及訪問實體的方法。使用 Repository 例項就是將其依賴注入到客戶端中。
例 3. 訪問 Person 實體
@ExtendWith(SpringExtension.class)
@ContextConfiguration
class PersonRepositoryTests {
@Autowired PersonRepository repository;
@Test
void readAll() {
List<Person> persons = repository.findAll();
assertThat(persons.isEmpty(), is(false));
}
}
該示例使用 Spring 的單元測試支援建立一個應用程式上下文,該上下文將對測試用例執行基於註解的依賴注入。在測試方法中,我們使用 Repository 查詢資料儲存。