Basic Spring Configuration
-----------------------------------1.application.properties -----------------------
driver=MySQLDriver
url=jdbc:mysql
-----------------------------------2.AppConfig.java -----------------------------------
package com.sunil;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
@ComponentScan(basePackages="com.sunil.bean")
@PropertySource("sunil.properties")
public class AppConfig {
}
-----------------------------------3.DbCon.java------------------------------------------
package com.sunil.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class DbCon {
@Value("${url}")
private String url;
@Value("${driver}")
private String driver;
@Override
public String toString() {
return "DbCon [url=" + url + ", driver=" + driver + "]";
}
}
------------------------------------4.Test .java without AppConfig.class---------------------------------
public class Test {
public static void main(String[] args) {
//Creating Spring Container Reference
AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext();
//Scan all the class file in below package
ac.scan("com.sunil.bean");
//create object,provide data,link object
ac.refresh();
//read the object from spring Container
Object ob=ac.getBean("dbCon","DbCon.class");
//print the object
System.out.println(ob);
//Destroy the object in Spring Container
ac.close();
}
}
-----------------------------------5.Test1.java with AppConfig.class------------------------------------
public class Test1 {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext(AppConfig.class);
Object ob=ac.getBean("dbCon","DbCon.class");
System.out.println(ob);
ac.close();
}
}
No Comments Yet!!