java spring入门小程序_第一个Spring小程序实战

ps:本文偏向原理和操作性,原理适合于任何编译器。

支持Spring入门,目的是在xml文件里面装配相关bean(java对象),并实现获取。(IOC)

一、先建立一个Spring新项目,添加maven(此处自行百度如何配置maven)

Spring至少需要六个包:

9k=

用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文件大约长这样:

d7ac3cfc4a85d4999605ab6deda2ad80.png

这就配置好了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文件,输出如下:

4717c6c4e9b1c7886a01eb7d9759ac4c.png

大功告成!!

总结:

IOC(控制反转)也叫  DI(依赖注入),无论要什么对象,都可以去springIoc中获取,而不需要自己操作。

Spring发展史:

1.new,set对象

2.简单工厂

3、IOC(超级工厂)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值