Creating simple Json objects in Javascript example


Here is one example to create JSON object in java script

<html>
<head>
<title>Creating json object</title>
<script language="javascript" >
var jsonObject = {"address":"Bangalore","designation":"Open source Publisher","employer":"Self Business","name":"Vinod"}
document.write("<h1>JSON Object Details</h1>");
document.write("<br>");
document.write("<h3>name="+jsonObject.name+"</h3>");
document.write("<h3>Address="+jsonObject.address+"</h3>");
document.write("<h3>designation="+jsonObject.designation+"</h3>");
document.write("<h3>employer="+jsonObject.employer+"</h3>");
</script>
</head>
<body>
</body>
</html>
Output

Spring Beans AutoWiring examples

Spring Autowiring

Spring frameworks provides autowiring feature, it enables you to inject the object dependency implicitly. It internally uses setter or constructor injection.
it helps cut down on the amount of XML configuration you write for a big Spring based application.

Types of Autowiring

There are couple of autowiring modes which can be used to instruct Spring container to use autowiring for dependency injection. Some of them are

no
This is default setting which means no autowiring and you should use explicit bean reference for wiring.
byName
Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file.
byType
Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file.
constructor
Similar to byType, but type applies to constructor arguments.
autodetect
Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType

XML Based example

We have below two classes, CarInsurance and CarOrder and in CarOrder class we want to inject CarInsurance class, 

CarInsurance.java

public class CarInsurance {
    private String name;
    private String policyDetails;
//Getters and setters

CarOrder.java

public class CarOrder {

    private String carDetails;
    private CarInsurance carInsurance;
    public CarOrder(CarInsurance carInsurance) {
        super();
        this.carInsurance = carInsurance;
    }  
    public CarOrder() {}
//Getters and setters

Next, our goal is to inject CarInsurance bean to CarOrder bean..

<!-- Car insurance bean -->
    <bean id="carInsurance" class="com.vinod.test.CarInsurance">
        <property name="name" value="Progressive" />
        <property name="policyDetails" value="Full cover" />
    </bean>
   
    <!-- Autowiring by name -->
    <bean id="carOrder" class="com.vinod.test.CarOrder" autowire="byName">
    </bean>
   
    <!-- Autowiring by constructor -->
    <bean id="carOrder1" class="com.vinod.test.CarOrder"  autowire="constructor">
    </bean>

The above configuration, the bean carOrder will get the CarInsurance bean reference via auto wiring by name as we declared the property name in CarOrder, the second bean carOrder1 bean will get the CarInsurance reference via constructor as we defined the Constructor in CarOrder.

Annotation based Autowiring example

Annotation based auto wiring is very easy and it helps to inject dependencies via @Autowired annotation., see this example

1. Do the component scan in our Spring configuration


import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.vinod.test")
public class MySpringConifg {
   
}

2. Create Java components with @Component annotaions

package com.vinod.test;
import org.springframework.stereotype.Component;

@Component
public class Customer {
    public String getCustomer() {
        return "Thomas....Regular customer";
    }
}
 

 

package com.vinod.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CustomerDetails {
    @Autowired
    Customer customer;
    public Customer getCustomerDetails() {
        return customer;
    }
}
 

The CustomerDetails class we are using the @Autowired annotation to inject Customer bean, let us execute this program

3. Test class

package com.vinod.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class CustomerTest {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(MySpringConifg.class);
        context.refresh();
        CustomerDetails cd = context.getBean(CustomerDetails.class);
        System.out.println(cd.getCustomerDetails().getCustomer());
    }

}
 

Output

Thomas....Regular customer

 

Done!!!!

Download this complete example..

https://github.com/kkvinodkumaran/spring



Spring Injecting Collection Example

Spring Injecting Collection

Spring framework facilitates to configure primitive data type using value attribute and object reference using ref attribute of the <property> tag. Both the cases it is dealing with passing singular value to bean. But Spring provides the option to pass the plural values like Java Collection types List, Set, Mat etc.
Here is one example to pass List of items to the bean from the configuration xml file

Example

1. Create Order. java

package com.pretech.dependency;
 
import java.util.ArrayList;
 
public class Order {
 
    private String orderNumber;
    private ArrayList orderItems;
 
    public ArrayList getOrderItems() {
        return orderItems;
    }
 
    public void setOrderItems(ArrayList orderItems) {
        this.orderItems = orderItems;
    }
 
    public String getOrderNumber() {
        return orderNumber;
    }
 
    public void setOrderNumber(String orderNumber) {
        this.orderNumber = orderNumber;
    }
}

2. Create spring configuration file (OrderDetails.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
   <bean id="Order" class="com.pretech.dependency.Order">
      <property name="orderNumber" value="1212" />
    <property name="orderItems">
    <list>
        <value>PEPSI</value>
        <value>COCA-COLA</value>
        <value>MIRINDA</value>
        <value>FANTA</value>
    </list>
</property>
    </bean>
</beans>
Note: Added List and its values

4. Create a Main program (OrderDetails.java)

package com.pretech.dependency;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class OrderDetails {
 
    /**
     * @param args
     */


    public static void main(String[] args) {
 
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "OrderDetails.xml");
        Order order = (Order) context.getBean("Order");
        System.out.println("Order item details "+order.getOrderNumber()""+order.getOrderItems());
    }
 
}
 

5. Output


Order item details 1212  [PEPSI, COCA-COLA, MIRINDA, FANTA]

Spring Injecting Inner Beans Example

Inner beans are beans that are defined within the scope of another bean. Inner bean we can add to beans property or constructor-arg tag

See this below example (Insurance class bean is injecting to Car class)

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">


    <!-- Setter based dependency injection -->
    <!-- Here car order is the parent class and injecting the car insurance
        bean as property and doing the car insurance bean creation there itself -->
    <bean id="carOrder" class="com.vinod.test.CarOrder">

        <property name="carInsurance">
            <bean id="carInsurance" class="com.vinod.test.CarInsurance">
                <property name="name" value="Progressive" />
                <property name="policyDetails" value="Full cover" />
            </bean>
        </property>
    </bean>

</beans>    

Spring Dependency Injection (Constructor and Setter based) Example

When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while doing unit testing. Dependency Injection helps in gluing these classes together and same time keeping them independent

We can achieve more reusable code,more testable code,more readable code using dependency injection

Spring provides two ways of Dependency injection

1. Constructor based

Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.

2. Setter method

Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

Here is one simple examples for both,

Use case: When buying a car they want to update the insurance details as well, basically when creating a Car Order object we need to add insurance as well..

Spring configuration details

Here we are creating the CarOrder bean based one setter injection and constructor injection as well.

 

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

   
    <bean id="carInsurance" class="com.vinod.test.CarInsurance">
        <property name="name" value="Progressive" />
        <property name="policyDetails" value="Full cover" />
    </bean>
   
    <!-- Setter based dependency injection -->
    <bean id="carOrder" class="com.vinod.test.CarOrder">
            <property name="carInsurance" ref="carInsurance" />
    </bean>
   
    <!-- Constructor based dependency injection -->
    <bean id="carOrder1" class="com.vinod.test.CarOrder">
              <constructor-arg ref="carInsurance" />

    </bean>
</beans>    


CarInsurance.java

package com.vinod.test;

public class CarInsurance {
    private String name;
    private String policyDetails;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPolicyDetails() {
        return policyDetails;
    }
    public void setPolicyDetails(String policyDetails) {
        this.policyDetails = policyDetails;
    }
    @Override
    public String toString() {
        return "CarInsurance [name=" + name + ", policyDetails=" + policyDetails + "]";
    }

}
 


CarOrder.java

package com.vinod.test;

public class CarOrder {

    private String carDetails;
    private CarInsurance carInsurance;
    public String getCarDetails() {
        return carDetails;
    }
    public void setCarDetails(String carDetails) {
        this.carDetails = carDetails;
    }
    public CarInsurance getCarInsurance() {
        return carInsurance;
    }
    public void setCarInsurance(CarInsurance carInsurance) {
        this.carInsurance = carInsurance;
    }
    public CarOrder(CarInsurance carInsurance) {
        super();
        this.carInsurance = carInsurance;
    }
    public CarOrder() {}
    @Override
    public String toString() {
        return "CarOrder [carDetails=" + carDetails + ", carInsurance=" + carInsurance + "]";
    }
   
}
 


Test class

package com.vinod.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDIExample {

    public static void main(String[] args) {

        // Test Setter based dependency injection
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-di-core.xml");

        CarOrder cardOder = (CarOrder) context.getBean("carOrder");
        System.out.println(cardOder);

        // Test Constructor based dependency injection

        ApplicationContext context1 = new ClassPathXmlApplicationContext("spring-di-core.xml");

        CarOrder cardOder1 = (CarOrder) context1.getBean("carOrder1");
        System.out.println(cardOder1);
    }

}
 


Output

CarOrder [carDetails=null, carInsurance=CarInsurance [name=Progressive, policyDetails=Full cover]]

CarOrder [carDetails=null, carInsurance=CarInsurance [name=Progressive, policyDetails=Full cover]]

 

Download Example

https://github.com/kkvinodkumaran/spring

Spring Bean Definition Template Example

Spring Bean Definition Template

We can create a Bean definition template which can be used by other child bean definitions without any additional coding. While defining a Bean Definition Template, you should not specify class attribute and should specify abstract attribute with a value of true as shown below:

Here is one simple example as Vechicle class is parent and Car class is child and Car class is getting wheel property via inheritance configured in the xml

Example

1. Create a Parent class (Vechicle.java)

package com.inheritance;

public class Vehicle {

    private String wheel;

    public String getWheel() {
        return wheel;
    }

    public void setWheel(String wheel) {
        this.wheel = wheel;
    }
}

2. Create a Child class (Car.java)

package com.inheritance;

public class Car {
    private String dicky;
    private String wheel;

    public String getWheel() {
        return wheel;
    }

    public void setWheel(String wheel) {
        this.wheel = wheel;
    }

    public String getDicky() {
        return dicky;
    }

    public void setDicky(String dicky) {
        this.dicky = dicky;
    }
}

3. Create Beans configuration file (VehicleTemplate.xml)

 Add bean details

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="vehicle"   abstract="true">
    <property name="wheel" value="Four wheeler"/>        </bean>
    <bean id="car" class="com.inheritance.Car" parent="vehicle">
    <property name="dicky" value="Flat dicky"/>    </bean>
</beans>

Note: In the above car bean definition mentioned the parent bean.

4. Create a Main program (VehicleTemplateMain.java)

 

package com.inheritance;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class VehicleTemplateMain {

    /**
     * @param args
     */
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext(
                "VehicleTemplate.xml");
        Car c = (Car) context.getBean("car");
        System.out.println("From vehicle abstract   "+c.getWheel());
        System.out.println("From car"+c.getDicky());

    }

}

 

5. Output

 

From vehicle abstract   Four wheeler
From carFlat dicky

Spring Bean Definition Inheritance Example

Spring Bean Definition Inheritance

Spring Bean definition inheritance has nothing to do  with Java class inheritance but inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit required configuration from the parent bean

Here is one simple example as Vehicle class is parent and Car class is child and Car class is getting wheel property via inheritance configured in the xml

Example

1. Create a Parent class (Vehicle.java)

package com.inheritance; 
public class Vehicle { 
    private String wheel; 
    public String getWheel() {
        return wheel;
    } 
    public void setWheel(String wheel) {
        this.wheel = wheel;
    }
} 

2. Create a Child class (Car.java)

package com.inheritance; 
public class Car {
    private String dicky;
    private String wheel; 
    public String getWheel() {
        return wheel;
    } 
    public void setWheel(String wheel) {
        this.wheel = wheel;
    } 
    public String getDicky() {
        return dicky;
    } 
    public void setDicky(String dicky) {
        this.dicky = dicky;
    }
} 

3. Create Beans configuration file (Vehicle.xml)


 Add bean details

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="vehicle" class="com.inheritance.Vehicle">
<property name="wheel" value="Four wheeler"/>
</bean>
<bean id="car" class="com.inheritance.Car"
parent="vehicle">
<property name="dicky" value="Flat dicky"/>
</bean>
</beans> 

Note: In the above car bean definition mentioned the parent bean.

4. Create a Main program (CarMain.java)

package com.inheritance; 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class CarMain { 
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "Vehicle.xml");
        Vehicle v = (Vehicle) context.getBean("vehicle");
        System.out.println("From Vehicle"+v.getWheel());
        Car c = (Car) context.getBean("car");
        System.out.println("From car"+c.getWheel());
        System.out.println("From car"+c.getDicky()); 
    } 
}

5. Project Structure




image 


6. Output


From VehicleFour wheeler
From carFour wheeler
From carFlat dicky

Java URL client for Web services

Restful Java client using Java.Net.URL

Example

package com.vinod.vinod_rest_examples;

import java.io.*;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MyURLClient {

    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8080/xxxxx");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/xml");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String response;
            System.out.println("Response from web service :");
            while ((response = br.readLine()) != null) {
                System.out.println(response);
            }
            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }
    }

}
 

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts