初识spring,IOC
bean是spring中最核心的东西,因为spring就像是个大水桶,而bean就像是容器中的水,水桶脱离了水便没什么用处了,那么我们先定义个bean:
public class UserService {
public void sing(){
System.out.println("唱歌------");
}
}
很普通,bean没有任何特别之处,接下来我们看看配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--id用户区分bean的标识-->
<bean id="userService" class="com.adwo.UserService" ></bean>
</beans>
在上面的配置文件中,我们看到了bean的声明方式,尽管spring中bean的元素定义着N种属性来支撑我们业务的各种应用,但是我们只要声明成这样,基本上就已经满足我们的大多数应用了,接下来我们编写测试代码:
public class UserTest {
public static void main(String[] args) {
String path="beans.xml";
//加载类路径下的配置文件
ApplicationContext app = new ClassPathXmlApplicationContext(path);
UserService userService = (UserService) app.getBean("userService");//根据bean的id获取实体
userService.sing();
}
打印如下:
唱歌------
好了,一个完整的spring入门实例到这里就结束了,那我们来好好的分析一下上面的测试代码的功能,来探索上面的测试代码中spring究竟帮助我们完成了什么工作?这段测试代码完成的功能就一下几点:
1、读取配置文件beans.xml。
2、根据beans.xml中的配置找到对应的类的配置,并实例化。
3、调用实例化后的实例。
其实这就是spring的IOC,即 Inverse of Control控制反转,就是将原本在程序中创建UserService对象的控制权,交由spring框架管理,简单的说,就是创建UserService 对象的控制权被反转到了spring框架。
传统的方式是:
public static void main(String[] args) {
//传统自己创建new
UserServiceservice = new UserService();
service.sing();
}