Spring是什么?
Spring框架是由于软件开发的复杂性而创建的。Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅仅限于服务器端的开发。从简单性、可测试性和松耦合性角度而言,绝大部分Java应用都可以从Spring中受益。
◆目的:解决企业应用开发的复杂性
◆功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能
◆范围:任何Java应用
Spring是一个轻量级控制反转(IoC)和面向切面(AOP)的容器框架。
一、搭建开发环境(Eclipse)
1.引入jar包&安装spring tools 4 suit插件
2.构建代码
HelloWorld:
public class HelloWorld {
private String name;
public void setName(String name) {
System.out.println(name);
this.name = name;
}
public void hello() {
System.out.println("hello: " + name);
}
public HelloWorld() {
// TODO Auto-generated constructor stub
System.out.println("constructor!");
}
}
- 普通调用
public static void main(String[] args) {
// 创建HelloWorld的一个对象
HelloWorld helloWorld = new HelloWorld();
// 设置用户名
helloWorld.setName("tom");
// 调用hello方法
helloWorld.hello();
}
- Spring容器调用
<?xml version="1.0" encoding="UTF-8"?>
<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,
class:通过反射实现,要求bean中必须有无参构造函数
id:容器中ID唯一
-->
<bean id="hello" class="xxx.xxx.HelloWorld">
<property name="name" value="lucy"></property>
</bean>
</beans>