ps:本文偏向原理和操作性,原理适合于任何编译器。
支持Spring入门,目的是在xml文件里面装配相关bean(java对象),并实现获取。(IOC)
一、先建立一个Spring新项目,添加maven(此处自行百度如何配置maven)
Spring至少需要六个包:
用maven添加这六个包的依赖代码如下:
org.springframework
spring-aop
5.1.4.RELEASE
org.springframework
spring-beans
5.1.1.RELEASE
org.springframework
spring-context
5.1.3.RELEASE
org.springframework
spring-core
5.1.3.RELEASE
org.springframework
spring-expression
5.1.3.RELEASE
commons-logging
commons-logging
1.1.1
二、建立一个实体类:
诸如学生类:
packageentity;public classStudent {private intstuNo;privateString name;privateString score;public intgetStuNo() {returnstuNo;
}public void setStuNo(intstuNo) {this.stuNo =stuNo;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}publicString getScore() {returnscore;
}public voidsetScore(String score) {this.score =score;
}
@OverridepublicString toString() {return "Student{" +
"stuNo=" + stuNo +
", name='" + name + '\'' +
", score='" + score + '\'' +
'}';
}
}
三、而使用Spring的一个核心是使用xml文件配置bean(IOC),实质上可以创建对象并赋值:
我们新建一个ApplicationContext.xml文件(格式是Spring配置文件格式)
在里面添加bean:
bean的格式:
添加后的xml文件大约长这样:
这就配置好了Student类的各个对象
四、新建Main类,我们在此类中获取并输出:
importentity.Student;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;public classMain {public static voidmain(String[] args){
ApplicationContext context= new ClassPathXmlApplicationContext("ApplicationContext.xml");//括号内写xml文件路径
Student student1= (Student)context.getBean("student1");
Student student2= (Student)context.getBean("student2");
System.out.println(student1);
System.out.println(student2);
}
}
之后运行Main文件,输出如下:
大功告成!!
总结:
IOC(控制反转)也叫 DI(依赖注入),无论要什么对象,都可以去springIoc中获取,而不需要自己操作。
Spring发展史:
1.new,set对象
2.简单工厂
3、IOC(超级工厂)