Spring constructor namespace tutorial shows how to use c-namespace in constructor-based injection in a Spring application.
last modified October 18, 2023
Spring constructor namespace tutorial shows how to use c-namespace in constructor-based injection in a Spring application.
Spring is a popular Java application framework for creating enterprise applications.
Spring c-namespace is an XML shortcut and replacement of the <constructor-arg/> subelement of the <bean/> tag. To enable the c-namespace feature, we need to add the xmlns:c=“http://www.springframework.org/schema/c" into the XML file. Note that this namespace does not have a separate XSD file; therefore, IDEs such as IntelliJ do not recognize it.
The application contains two User beans. One is injected with the older <constructor-arg/>, the other one with the newer c-namespace attribute.
src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ │ Application.java │ │ └───bean │ │ User.java │ └───resources │ logback.xml │ my-beans.xml └───test └───java
This is the project structure.
pom.xml
<?xml version=“1.0” encoding=“UTF-8”?> <project xmlns=“http://maven.apache.org/POM/4.0.0" xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.zetcode</groupId>
<artifactId>cnamespace</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<spring-version>5.3.23</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<mainClass>com.zetcode.Application</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
In the pom.xml file, we have basic Spring dependencies spring-core and spring-context and logging logback-classic dependency.
The exec-maven-plugin is used for executing Spring application from the Maven on the command line.
resources/logback.xml
<?xml version=“1.0” encoding=“UTF-8”?> <configuration> <logger name=“org.springframework” level=“ERROR”/> <logger name=“com.zetcode” level=“INFO”/>
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
</Pattern>
</encoder>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="consoleAppender" />
</root>
</configuration>
The logback.xml is a configuration file for the Logback logging library.
resources/my-beans.xml
<?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:c=“http://www.springframework.org/schema/c" xsi:schemaLocation=“http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="user1" class="com.zetcode.bean.User">
<constructor-arg name="name" value="John Doe"/>
<constructor-arg name="occupation" value="gardener"/>
</bean>
<bean name="user2" class="com.zetcode.bean.User"
c:name="Peter Smith" c:occupation="teacher"/>
</beans>
The my-beans.xml file declares two beans: user1 and user2. The user1 uses <constructor-arg/> to inject its values, while user2 uses c:name and c:occupation attributes.
com/zetcode/bean/User.java
package com.zetcode.bean;
public class User {
private String name;
private String occupation;
public User(String name, String occupation) {
this.name = name;
this.occupation = occupation;
}
@Override
public String toString() {
final var sb = new StringBuilder("User{");
sb.append("name='").append(name).append('\'');
sb.append(", occupation='").append(occupation).append('\'');
sb.append('}');
return sb.toString();
}
}
This is the User class that is managed by Spring container. It must contain a constructor because we use constructor-based injection in our application.
com/zetcode/Application.java
package com.zetcode;
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.GenericXmlApplicationContext;
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
var ctx = new GenericXmlApplicationContext("my-beans.xml");
var u1 = ctx.getBean("user1");
var u2 = ctx.getBean("user2");
logger.info("{}", u1);
logger.info("{}", u2);
ctx.close();
}
}
This is the main application class. It retrieves the two beans and prints them to the console.
$ mvn -q exec:java 16:40:39.632 INFO com.zetcode.Application - User{name=‘John Doe’, occupation=‘gardener’} 16:40:39.632 INFO com.zetcode.Application - User{name=‘Peter Smith’, occupation=‘teacher’}
We run the application.
In this article we have shown how to use constructor-based injection with c-namespace.
My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.
List all Spring tutorials.