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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.3.23</version>
</dependency>
</dependencies>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024