Spring Framework Tutorial
Software Setup and Configuration (STS/Eclipse/IntelliJ)
Core Spring
Spring Annotations
Spring Data
Spring JDBC
Spring Security
In Spring, the <util:constant>
tag allows you to access a static constant value from a class without having to instantiate the class. This can be helpful when you want to reference static constants from your Java classes directly in your Spring XML configuration.
Let's go through an example to see how this works.
Suppose you have a class named Constants
with a static constant named MAX_USERS
:
public class Constants { public static final int MAX_USERS = 100; }
To use the constant value in your Spring XML configuration, you'd first include the util
namespace and schema definition, and then you can use the <util:constant>
tag:
<?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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <!-- Accessing static constant from the Constants class --> <util:constant id="maxUsers" static-field="Constants.MAX_USERS"/> <!-- Now, you can use 'maxUsers' as a reference anywhere in the Spring configuration --> <bean id="userService" class="com.example.UserService"> <property name="userLimit" ref="maxUsers"/> </bean> </beans>
In the above configuration, the <util:constant>
tag fetches the static MAX_USERS
value from the Constants
class and defines a bean with the name maxUsers
holding that constant value. This bean can then be injected into other beans, such as the userService
bean, using the ref
attribute.
In the UserService
class, you can use the injected constant value like this:
public class UserService { private int userLimit; // Setter for injection public void setUserLimit(int userLimit) { this.userLimit = userLimit; } // Some method that uses the userLimit public void someMethod() { System.out.println("User Limit: " + userLimit); } }
This approach allows you to decouple configuration constants from your application logic, providing flexibility in configuration management.
Using util:constant
in Spring XML configuration:
util:constant
tag in Spring XML configuration to define constants.<util:constant static-field="com.example.MyConstants.MY_CONSTANT"/>
Defining constants with util:constant
in Spring:
util:constant
tag in Spring configuration.<util:constant static-field="com.example.MyConstants.API_KEY" value="my-api-key"/>
Accessing util:constant
values in Spring beans:
util:constant
in Spring beans.public class MyBean { @Value("#{T(com.example.MyConstants).MY_CONSTANT}") private String myConstant; }