spring:是一个大型的容器,用来管理协调各层之间的调用。
这里参考官方文档:https://spring.io/
这里使用maven进行构建。
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>5.2.3.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.2.3.RELEASEversion>
dependency>
private int deptno;
private String dname;
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
<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.xsd">
<bean id="dept" class="com.hx.spring.Dept">
<property name="deptno" value="101">property>
<property name="dname" value="技术部">property>
bean>
beans>
@Test
public void test1(){
//实例化ioc容器
ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
//从容器中获取所需要的对象
Dept dept = (Dept) context.getBean("dept"); //括号中填写xml中配置的实体类的id
System.out.println(dept);
}
/**
* 类定义,用来解析每个类的信息
* @author Huathy
* @date 2020年3月4日
*/
public class ClassDefinition {
private String id; //唯一标识
private String className; //类的全路径
private Map<String,String> pros;
public ClassDefinition(String id, String className) {
super();
this.id = id;
this.className = className;
pros = new HashMap<String,String>();
}
public void addPro(String key, String value) {
pros.put(key, value);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Map<String, String> getPros() {
return pros;
}
public void setPros(Map<String, String> pros) {
this.pros = pros;
}
}
/**
*
* @author Huathy
* @date 2020年3月4日
*/
public interface ApplicationContext {
public Object getBean(String id);
}
/**
*
* @author Huathy
* @date 2020年3月4日
*/
public class ClassPathXmlApplicationContext implements ApplicationContext {
private Map<String,Object> singeton = new HashMap<String,Object>();
private List<ClassDefinition> beans = new ArrayList<>();
public ClassPathXmlApplicationContext(String path) {
parseXml(path);
try {
makeInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
private void makeInstance() throws Exception {
if(beans.isEmpty()){
return;
}
Class c = null;
Method[] methods = null;
Map<String,Method> map = null;
String methodName = null;
Object obj = null;
Map<String,String> properties = null;
Method md = null;
String typeName = null;
for(ClassDefinition cls : beans){
c = Class.forName( cls.getClassName() );
obj = c.newInstance();
properties = cls.getPros();
if(properties == null || properties.isEmpty()){
singeton.put(cls.getId(), obj);
continue;
}
methods = c.getDeclaredMethods();
map = new HashMap<String,Method>();
for(Entry<String, String> entry : properties.entrySet()){
methodName = entry.getKey();
methodName = "set" + methodName.substring(0,1).toUpperCase() + methodName.substring(1);
md = map.get(methodName);
if(md == null){
continue;
}
typeName = md.getParameterTypes()[0].getSimpleName();
if( "int".equals(typeName) || "Integer".equals(typeName) ){
md.invoke(obj, Integer.parseInt(entry.getValue()));
}else if( "float".equals(typeName) || "Float".equals(typeName) ){
md.invoke(obj, Float.parseFloat(entry.getValue()));
}else if( "double".equals(typeName) || "Double".equals(typeName) ){
md.invoke(obj, Double.parseDouble(entry.getValue()));
}else{
md.invoke(obj, entry.getValue());
}
}
singeton.put(cls.getId(), obj);
}
}
/**
* 解析xml文件
* @param path
*/
private void parseXml(String path){
SAXReader read = new SAXReader();
Document doc = null;
try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(path)){
doc = read.read(is);
XPath xpath = doc.createXPath("//hx:bean"); //查找hx下的bean
//这里需要对命名空间进行处理
Map<String,String> nsmap = new HashMap<>();
nsmap.put("hx", "http://www.springframework.org/schema/beans"); //使用hx来替代后面的
xpath.setNamespaceURIs(nsmap); //设置命名空间信息
List<Element> nodes = xpath.selectNodes(doc);
if(nodes.isEmpty()){
return; //判断xml中是否配置,如果没有配置,直接返回
}
String id = null;
String className = null;
ClassDefinition bean = null;
List<Element> properties = null;
for(Element el : nodes){
id = el.attributeValue("id");
className = el.attributeValue("class");
bean = new ClassDefinition(id, className);
properties = el.elements(); //取出这个bean对象的属性值
if(properties != null && !properties.isEmpty()){
for(Element pro : properties){
//循环所有属性值
bean.addPro(pro.attributeValue("name"),pro.attributeValue("value"));
}
}
beans.add(bean);
}
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
@Override
public Object getBean(String id) {
return singeton.getOrDefault(id, null);
}
}
public class Dept implements Serializable{
private int deptno;
private String dname;
private List<Emp> emps;
public List<Emp> getEmps() {
return emps;
}
public void setEmps(List<Emp> emps) {
this.emps = emps;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + deptno;
result = prime * result + ((dname == null) ? 0 : dname.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Dept other = (Dept) obj;
if (deptno != other.deptno)
return false;
if (dname == null) {
if (other.dname != null)
return false;
} else if (!dname.equals(other.dname))
return false;
return true;
}
@Override
public String toString() {
return "Dept [deptno=" + deptno + ", dname=" + dname + "]";
}
public Dept(int deptno, String dname) {
super();
this.deptno = deptno;
this.dname = dname;
}
public Dept() {
super();
}
}
<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.xsd">
<bean id="dept" class="com.hx.spring.entity.Dept">
<property name="deptno" value="101">property>
<property name="dname" value="技术部">property>
bean>
beans>
public class AppTest {
@Test
public void test1(){
//实例化ioc容器
ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
//从容器中获取所需要的对象
Dept dept = (Dept) context.getBean("dept"); //括号中填写xml中配置的实体类id
System.out.println(dept);
}
}