Wednesday 17 October 2012

Using security namespace as the default namespace

In Spring in Action, 3rd edition, page 227, it says since the security-specific configuration is separated into a separate Spring configuration file, we can change the security namespace to be the primary namespace.

So old version:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security 
        http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <security:http auto-config="true" use-expressions="true">
        ....
    </security:http>
</beans>

And new version:

<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/security"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http auto-config="true" use-expressions="true">
        ....
    </http>

</beans:beans>

One thing I don't understand is why change beans to beans:beans. Why does the top element need a namespace?

Then I try to remove the namespace, the XML complains "Cannot find the declaration of element 'beans'".

Well, after reading the article XML Schema: Understanding Namespaces, I come to understand that the scope of a namespace begins at the element where it is declared. Therefore, in the old version, the element beans is associated with the default namespace (http://www.springframework.org/schema/beans),  in the new version, if we remove the namespace for the beans element, the element will be associated with the security namespace. But of course, the security schema doesn't define a beans element. Hence the complaint of the XML.

Let me rename the prefix of the beans namespace so that it looks more clear.

<bean123:beans xmlns:bean123="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/security"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http auto-config="true" use-expressions="true">
        ....
    </http>

</bean123:beans>