Beside using the <property>
element, Spring framework also provide us another way to wiring value or reference into the bean. We can use the Spring’s p
namespaces. The p
namespace has a schema URI of `http://www.springframework.org/schema/p`.
With this namespace declared in the Spring configuration file you can use the p:
prefixed attribute of the <bean>
element to wire bean’s property.
We update the configuration used in the previous example How do I inject into bean properties? to use the p
namespace. Here is the new Spring’s configuration file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="rectangle" class="org.kodejava.spring.core.Rectangle" />
<bean id="drawingBean" class="org.kodejava.spring.core.DrawingBean" p:colour="Red" p:shape-ref="rectangle" />
</beans>
The p:color
attribute set the color property to Red, this is a simple value. To set the shape property we use the p:shape-ref
attribute. The -ref
suffix tell Spring that we are injecting a reference.
You can use the <property>
element or using the p
namespace to inject bean’s property. Both of them have the same functionality.
Maven Dependencies
<dependencies>
<!-- https://search.maven.org/remotecontent?filepath=org/springframework/spring-core/5.3.23/spring-core-5.3.23.jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.23</version>
</dependency>
<!-- https://search.maven.org/remotecontent?filepath=org/springframework/spring-beans/5.3.23/spring-beans-5.3.23.jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.23</version>
</dependency>
<!-- https://search.maven.org/remotecontent?filepath=org/springframework/spring-context-support/5.3.23/spring-context-support-5.3.23.jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.3.23</version>
</dependency>
</dependencies>
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023