. @Annotations approach
·
Here we use
@postconstrct and @predestroy on top of methods
·
To activation
we configure CommonAnnotationBeanPostProceesor in xml
·
<defaulut-init-method,
defaulut-destgroy-method> for all Bean Classes
package bean;
public class Test {
private String url ;
private String uname ;
private String pwd;
Connection con;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@PostConstruct
public void myInit() throws Exception {
// TODO Auto-generated method stub
System.out.println("OWn init.........................");
// TODO Auto-generated method stub
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,uname,pwd);
if(con!=null){
System.out.println("Connected...........");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void getData() throws Exception{
System.out.println("Enter id : ");
Scanner sc = new Scanner(System.in);
String id = sc.next();
String qy ="select * FROM
student where sno = "+id;
java.sql.ResultSet rs = con.createStatement().executeQuery(qy);
if(rs.next()){
System.out.println("--------------------------");
System.out.println(rs.getString(1)+":"+rs.getString(2));
}else{
myDestroy();
}
}
@PreDestroy
public void myDestroy() throws Exception {
System.out.println("OWn Closed.........................");
}
}
package driver;
import org.springframework.context.ConfigurableApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import bean.Test;
public class Client {
public static void main(String[] args) throws Exception{
ConfigurableApplicationContext
context = new ClassPathXmlApplicationContext("res/s.xml");
Test t= (Test)context.getBean("c");
t.getData();
}
}
<beans>
<bean class="bean.Test"
id="c">
<property name="url"
value="jdbc:mysql://localhost:3306/test"></property>
<property name="uname"
value="root"></property>
<property name="pwd"
value="root"></property>
</bean>
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"></bean>
</beans>