ktm*_*124 3 java spring javabeans spring-ldap
我正在编写Spring LDAP应用程序,我必须为ContextSource设置身份验证策略.我想在我的bean XML文件中执行此操作.在为好的ContextSource JavaDoc的说,它有一个叫做setter方法
setAuthenticationStrategy(
DirContextAuthenticationStrategy authenticationStrategy
)
Run Code Online (Sandbox Code Playgroud)
要从我的beans文件调用此setter,以下XML是否足够?
<bean id="authStrategy"
class="org.springframework...DefaultTlsDirContextAuthenticationStrategy">
...
</bean>
<bean id="contextSource"
class="org.springframework.ldap.core.support.LdapContextSource">
<property name="url" ... />
<property name="base" ... />
...
<property name="authenticationStrategy" ref="authStrategy" />
</bean>
Run Code Online (Sandbox Code Playgroud)
也就是说,究竟是什么决定了方法的调用setAuthenticationStrategy?这是我的财产名称authenticationStrategy吗?Spring会自动将属性名称转换为适当的setter方法吗?
实际上,您误解了JavaBean上下文中"属性"一词的含义.
JavaBeans标准(Spring紧随其后)将Bean属性定义为具有遵循特定命名约定的Getter方法和/或Setter方法的东西:
对于属性'Bar foo',getter Bar getFoo()(或isFoo()布尔属性)或setter setFoo(Bar)必须存在(或两者),但不必是名为"foo"的字段.按照惯例,通常会有一个与属性同名的字段,但这绝不是必需的.
例如,下面的类(符合JavaBeans标准)具有Integer类型的bean属性"foo",尽管底层字段被调用iAmNotFoo并且是String类型.
public class Dummy {
private String iAmNotFoo;
public Integer getFoo() {
return Integer.valueOf(this.iAmNotFoo);
}
public void setFoo(final Integer foo) {
this.iAmNotFoo = foo.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
我们可以使用以下代码测试此假设:
public static void main(final String[] args) throws Exception {
for (final PropertyDescriptor descriptor :
Introspector
.getBeanInfo(Dummy.class, Object.class)
.getPropertyDescriptors()) {
System.out.println(
"Property: "
+ descriptor.getName()
+ ", type: "
+ descriptor.getPropertyType()
);
}
for (final Field field : Dummy.class.getDeclaredFields()) {
System.out.println(
"Field: "
+ field.getName()
+ ", type: "
+ field.getType());
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
属性:foo,类型:类java.lang.Integer
字段:iAmNotFoo,类型:class java.lang.String
如上所述,Spring使用这种确切的机制来设置属性.所以当你配置这样的bean时
<bean class="Dummy">
<property name="foo" value="123" />
</bean>
Run Code Online (Sandbox Code Playgroud)
"foo"指的是bean属性"foo",因此指向setter setFoo()
这使得构造如下可能:
public class Dummy2 {
private List<String> foos;
public void setFoos(List<String> foos) {
this.foos = foos;
}
public void setFoo(String foo){
this.foos = Collections.singletonList(foo);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以按如下方式连接
<bean class="Dummy2">
<!-- either set a single value -->
<property name="foo" value="123" />
<!-- or a list of values -->
<property name="foos">
<util:list>
<value>Abc</value>
<value>Xyz</value>
<value>123</value>
<value>789</value>
</util:list>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
如您所见,setter方法与Spring相关,而不是实际字段.
因此,在JavaBeans中说:Field!= Property,尽管在大多数情况下,存在与属性相同类型和名称的字段.
| 归档时间: |
|
| 查看次数: |
4836 次 |
| 最近记录: |