How to inject value into spring bean instance variables
package com.java2novice.beans;
public class Employee
{
private int empId;
private String name;
private String role;
public int getEmpId()
{
return empId;
}
public void setEmpId(int empId)
{
this.empId
= empId;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name
= name;
}
public String getRole()
{
return role;
}
public void setRole(String role)
{
this.role
= role;
}
}
How to inject inner bean in spring
package com.java2novice.beans;
public class Order
{
private String item;
private String price;
private String address;
public String getItem()
{
return item;
}
public void setItem(String item)
{
this.item
= item;
}
public String getPrice()
{
return price;
}
public void setPrice(String price)
{
this.price
= price;
}
public String getAddress()
{
return address;
}
public void setAddress(String
address)
{
this.address
= address;
}
}
Set spring bean scope using annotation
package com.java2novice.beans;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
Scope("prototype")
public class PaymentGateway
{
private Order order;
public PaymentGateway(Order
ord)
{
this.order
= ord;
}
public void setOrder(Order ord)
{
this.order
= ord;
}
public void processOrder()
{
System.out.println("Processing
order: "+order.getItem());
}
}
How to invoke spring bean init and destroy methods
package com.java2novice.test;
import org.springframework.context.ConfigurableApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.beans.NetworkManager;
public class SpringDemo
{
public static void main(String a[])
{
String
confFile = "applicationContext.xml";
ConfigurableApplicationContext
context
=
new
ClassPathXmlApplicationContext(confFile);
NetworkManager
networkMng = (NetworkManager) context.getBean("netManager");
networkMng.readData();
context.close();
}
}
Spring bean initialization callback
package com.java2novice.beans;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.springframework.beans.factory.InitializingBean;
public class NetworkManager
implements InitializingBean
{
private HttpURLConnection
connection;
private String urlStr;
public void setUrlStr(String
urlStr)
{
this.urlStr
= urlStr;
}
public void afterPropertiesSet()
{
System.out.println("Inside
init() method...");
URL
obj;
try
{
obj
= new
URL(this.urlStr);
this.connection
= (HttpURLConnection) obj.openConnection();
}
catch (MalformedURLException
e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void readData()
{
try
{
int responseCode =
this.connection.getResponseCode();
System.out.println("Response
code: "+responseCode);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
No comments:
Post a Comment