IoC和DI是Spring的基础IoC是Inversion of Control的缩写,译为“控制反转”,还有的译为“控制反向”或者“控制倒置”。
Spring通过IOC容器管理,将创建对象的控制权限给IOC容器。
第一个Spring程序
实现步骤:
1.下在依赖包,通过地址“http://repo.spring.io/simple/libs-release-local/org/springframework/spring/4.3.6.RELEASE/”下载,其框架压缩包名称为spring-framework-4.3.6.RELEASE-dist.zip。
libs目录中的JAR包分为3类:
- 以RELEASE.jar结尾的是Spring框架class文件的压缩包。
- 以RELEASE-javadoc.jar结尾的是Spring框架API文档的压缩包。
- 以RELEASE-sources.jar结尾的是Spring框架源文件的压缩包。
在libs目录中,有4个Spring的基础包,它们分别对应Spring核心容器的4个模块:
包名 | 说明 |
---|---|
spring-core-4.3.6.RELEASE.jar | 包含 Spring框架基本的核心工具类,Spring其他组件都要用到这个包里的类 |
spring-beans-4.3.6.RELEASE.jar | 所有应用都要用到的JAR包,包含访问配置文件、创建和管理 Bean以及进行IoC或者DI操作相关的所有类 |
spring-context-4.3.6.RELEASE.jar | Spring提供了在基础 IoC功能上的扩展服务,还提供了许多企业级服务的支持,如任务调度、JNDI定位、EJB集成、远程访问、缓存、邮件服务以及各种视图层框架的封装等 |
spring-expression-4.3.6.RELEASE.jar | 定义了Spring的表达式语言 |
2.编写配置文件
编写Spring配置文件,在项目的根路径下src创建文件spring-config.xml。在Spring配置文件中创建HelloSpring类的实例并为类中的hello属性注入属性值。
<!-- bean中,属性id的值必须唯一,属性class的值为类的全类名-->
<bean id="helloWorld" class="bdqn.bean.HelloWorld">
<!-- 通过标签property 反射机制调用类HelloWorld的seter方法,并为参数赋值-->
<property name="message">
<value>西瓜好吃(#^.^#)</value>
</property>
</bean>
3.编写测试代码
通过Spring进行属性注入,关键代码如下:
public static void main(String[] args) {
//加载xml文件,读取JavaBean,通过反射获取类的实例对象
ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
//通过bean的id获取指定类的HelloWorld实例对象
HelloWorld helloWorld= (HelloWorld) context.getBean("helloWorld");
System.out.println(helloWorld.getMessage());
HelloServiceImpl helloService = (HelloServiceImpl) context.getBean("helloService");
helloService.addMessage();
logger.info("log:info "+helloWorld.getMessage());
}
Spring初始化运行环境的2中方式:
//ClassPathXmlApplicationContext 是读取 src 目录下的配置文件
ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
// FileSystemXmlApplicationContext 即系统文件路径,文件的目录。
// (注意:如果你的xml文件放在WEB-INF文件夹下,需要用这个,否则会找不到该文件)
ApplicationContext context2=new FileSystemXmlApplicationContext("D:spring-config.xml");
通过id或类获取实例对象
HelloWorld helloWorld= (HelloWorld) context.getBean("helloWorld");
System.out.println(helloWorld.getMessage());
通过第一个Spring程序我们已经对Spring有了基本的理解,实现了通过Spring创建java类的实例,并对其属性以“注入”的方式进行赋值。那么,如果Java类的属性类型为JavaBean,如UserService中的UserDao,要怎么实现呢?下节课继续详解。(#^.^#)