Spring util:constant tag can be used to declare a bean which reference one class’s final static field. This article will show you how to do that.
1.Bound util namespace.
To use util:constant, you should first bound the util namespace for beans tag in application context xml file as below.
xmlns:util="http://www.springframework.org/schema/util"
2. Create CarBrand.java
This is java class represent car brand. It has two final static filed which are AUDI_BRAND and FORD_BRAND, the two field will be referenced later.
public class CarBrand { public final static CarBrand AUDI_BRAND = new CarBrand("Audi" , "Germany"); public final static CarBrand FORD_BRAND = new CarBrand("Ford" , "United States"); private String brandName; private String brandCountry; public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getBrandCountry() { return brandCountry; } public void setBrandCountry(String brandCountry) { this.brandCountry = brandCountry; } public CarBrand(String brandName, String brandCountry) { super(); this.brandName = brandName; this.brandCountry = brandCountry; } @Override public String toString() { StringBuffer retBuf = new StringBuffer(); retBuf.append("Brand Name : " + this.getBrandName()); retBuf.append(" , Brand Country : " + this.getBrandCountry()); return retBuf.toString(); } }
3. Create CarFactory.java
This class represent a car factory which will produce Audi and Ford cars. It has two properties for Audi brand and Ford brand car.
public class CarFactory { private CarBrand audiBrand; private CarBrand fordBrand; public CarBrand getAudiBrand() { return audiBrand; } public void setAudiBrand(CarBrand audiBrand) { this.audiBrand = audiBrand; } public CarBrand getFordBrand() { return fordBrand; } public void setFordBrand(CarBrand fordBrand) { this.fordBrand = fordBrand; } public static void main(String[] args) { // Initiate Spring application context, this line code will invoke bean initialize method. ApplicationContext springAppContext = new ClassPathXmlApplicationContext("BeanSettings.xml"); // Get the car factory bean. CarFactory carFactory = (CarFactory)springAppContext.getBean("carFactoryBean"); System.out.println(carFactory.getAudiBrand().toString()); System.out.println(carFactory.getFordBrand().toString()); } }
4. Use util:constant to declare beans.
The util:constant tag’s static-field attribute value is just the CarBrand class’s final static field AUDI_BRAND or FORD_BRAND.
<util:constant id="audiBrand" static-field="com.dev2qa.example.spring.bean.finalstatic.CarBrand.AUDI_BRAND" /> <util:constant id="fordBrand" static-field="com.dev2qa.example.spring.bean.finalstatic.CarBrand.FORD_BRAND" /> <bean id="carFactoryBean" class="com.dev2qa.example.spring.bean.finalstatic.CarFactory"> <property name="audiBrand" ref="audiBrand"></property> <property name="fordBrand" ref="fordBrand"></property> </bean>
5. Output
[download id=”2801″]