Search code examples
javaspringspring-java-config

What is the equivalent Java configuration for an XML p-namespace attribute?


For example., how can I convert the following to a JavaConfig @Bean?

<bean id="ldapDao" class="org.mycompany.LdapDAOImpl" p:ldapUrl-ref="ldapHost"/>

Here's where I'm at with the equivalent JavaConfig Bean

@Bean(name="ldapDao")
public LdapDAOImpl getLdapDAOImpl(){
    LdapDAOImpl ldapDAOImpl = new LdapDAOImpl();
    //How can I set the reference here to ldapHost?
    return new LdapDAOImpl();
}          

Solution

  • First, the p-namespace is defined as

    The p-namespace enables you to use the bean element’s attributes, instead of nested <property/> elements, to describe your property values and/or collaborating beans.

    In other words, it's just an alternative for defining bean properties.

    For example,

    <bean id="ldapDao" class="org.mycompany.LdapDAOImpl" p:ldapUrl-ref="ldapHost"/>
    

    is equivalent to

    <bean id="ldapDao" class="org.mycompany.LdapDAOImpl">
        <property name="ldapUrl" ref="ldapHost" />
    </bean>
    

    where the -ref suffix in the p: attribute is explained with an example in the documentation

    As you can see, this example includes not only a property value using the p-namespace, but also uses a special format to declare property references. Whereas the first bean definition uses <property name="spouse" ref="jane"/>to create a reference from bean john to bean jane, the second bean definition uses p:spouse-ref="jane" as an attribute to do the exact same thing. In this case spouse is the property name, whereas the -ref part indicates that this is not a straight value but rather a reference to another bean.

    Each property element appearing in your <bean> definition requires a corresponding setter in the bean class.

    Given all the above, the corresponding @Bean definition would be one that initializes an object of type org.mycompany.LdapDAOImpl and invokes its setLdapUrl setter with the object corresponding to the bean named ldapHost as an argument.

    For example, assuming you had such a bean

    @Bean
    public LdapHost ldapHost() {
        return new LdapHost();
    }
    

    you'd then use that to initialize your ldapDao

    @Bean
    public LdapDaoImpl ldapDao() {
        LdapDaoImpl ldapDao = new LdapDaoImpl();
        ldapDao.setLdapUrl(ldapHost());
        return ldapDao;
    }
    

    Alternatively, you can have Spring inject it for you.

    @Bean
    public LdapDaoImpl ldapDao(LdapHost ldapHost) {
        LdapDaoImpl ldapDao = new LdapDaoImpl();
        ldapDao.setLdapUrl(ldapHost);
        return ldapDao;
    }