Using literals

Using literals in SpEL enables the developers to set primitive values for the properties of the bean. Although using literals in configuration doesn't sound interesting, knowing how to use it in expression certainly helps us to go for the complex expressions. Follow these steps to understand the use of literals:

  1. Create Ch02_SpringEL as a Java application, and add to it Spring jars.
  2. Define Customer class in the com.ch02.beans package, as shown in the following lines of code:
public class Customer { 
  private String cust_name; 
  private String cust_id; 
  private boolean second_handed; 
  private double prod_price; 
  private String prod_name; 
  // getters and setters 
  // toString() 
} 
  1. Create beans.xml in the class path to configure the Customer bean, as follows:
<bean id="cust_new" class="com.ch02.beans.Customer"> 
  <property name="cust_name" value="Bina"/> 
  <property name="cust_id" value="#{2}"/> 
  <property name="prod_name" value="#{'Samsung Fridge'}"/> 
  <property name="prod_price" value="#{27670.50}"/> 
  <property name="second_handed" value="#{false}"/> 
</bean> 

You can observe the configured values for cust_id and prod_price using the SpEL syntax as #{ value}, and we will use single quotes to specify the value for prod_name. You can even use double quotes to specify String values. The cust_name value is configured in old style. Yes, it's still possible to use old style and SpEL together to set the values.

  1. Add TestCustomer.java, as shown in the following piece of code:
public static void main(String[] args) { 
  // TODO Auto-generated method stub 
  ApplicationContext context=new 
      ClassPathXmlApplicationContext("beans.xml");  
  Customer customer=(Customer)context.getBean("cust_new"); 
      System.out.println(customer); 
} 
  1. We will get the following output:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.27.232