spring框架-简单案例学习

    xiaoxiao2022-07-07  241

    spring是什么?

    struts是web框架(jsp/action/actionform)

    hibernate 是orm框架,处于持久层

    spring 是容器框架,用于配置bean,并维护bean之间关系的框架。

     

    spring 中有一个非常概念:bean (是java中任何一种对象,javabean/service/action数据源/dao,ioc(控制反转 inverse of control ),di(dependency injection 依赖注入)

    spring框架,他可以管理web层,业务层,dao层,持久层,该spring可以配置各个层的组件(bean),并维护各个bean直接按的关系。

     

    spring案例:

    1.下载springframework包

    (3)下载springframework包

    http://repo.spring.io/release/org/springframework/spring/4.3.9.RELEASE/spring-framework-4.3.9.RELEASE-dist.zip

    (4)下载spring依赖的日志包commons-logging

    http://commons.apache.org/proper/commons-logging/download_logging.cgi

     

    2.引入spring的开发包。

    新建一个项目myspring1,在项目中新建一个文件夹lib,将spring框架的jar包和谐日志包common-logging.jar复制到这个文件夹中。然后选中所有的jar包,右键->Build Path->Add to Build Path。

    在进行以上操作后,就会生成一个Referenced Libaraies文件。

    3.在src中新建包com.service。并在此包下新建类UserService.java。在UserService中添加以下代码:

    package com.service; public class UserService { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void sayHello(){ System.out.println("Hello "+name); } }

     

    在项目src目录下创建spring核心文件 applicationContext.xml ,在文件添加如下代码:(在该文件引入xsd文件,并在里面配置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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userService" class="com.service.UserService"> <property name="name"> <value>Spring 哈哈!</value> </property> </bean> </beans>

    在src中新建包com.test ,并在此包中添加类Test.java,在Test.java中添加一下代码:

    package com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.service.UserService; public class Test { public static void main(String[] args) { //spring 方法 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService us = (UserService) ac.getBean("userService"); us.sayHello(); } }

    4.运行Test.java文件就可以看到控制台下的打印信息了

     

    最新回复(0)