Spring学习总结之基础篇

struts web 框架 (jsp/action/actionfrom)

hibernate orm(对象关系映射) 框架 , 处于持久层 .

spring 是容器框架 , 用于配置 bean (service/dao/domain/action/ 数据源 ) , 并维护 bean 之间关系的框架

model层:业务层+dao层+持久层


service类:

package com.service;

public class UserService {
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void sayHello(){
        System.out.println("你好:"+name);
    }

}


applicationContext.xml文件:

<!-- bean 元素的作用是,当我们的 spring 框架加载时候, spring 就会自动的创建一个 bean 对象,并放入内存
UserService userSerivce=new UserService();
userSerivce.setName(" 张三 ");

当ClassPathXmlApplicationContext("applicationContext.xml");执行的时候,我们的spring容器对象被创建,同时
applicaionContext.xml中配置的bean就会被创建(内存[Hashmap/HashTable])


-->
<bean id="userservice" class="com.service.UserService">
<property name="name">
<value>
张三 </value>
</property>
</bean>


测试类:

//UserService userService=new UserService();
//userService.setName("chenzheng");
//userService.sayHello();
       
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService=(UserService) ac.getBean("
userservice ");
userService.sayHello();


spring 是一个容器框架,可以配置各种 bean(action/service/domain/dao), 并且可以维护 bean bean 的关系 , 当我们需要使用某个 bean 的时候,可以 使用 getBean(id) 即可 .

 

ioc(inverse of controll ) 控制反转 : 所谓控制反转就是把创建对象 (bean), 和维护对象 (bean) 的关系的权利从程序中转移到 spring 的容器 (applicationContext.xml), 而程序本身不再维护 .


di(dependency injection) 依赖注入 : 实际上 di ioc 是同一个概念, spring 设计者认为 di 更准确表示 spring 核心技术


创建工具类ApplicaionContextUtil.java:

package com.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

final public class ApplicaionContextUtil {

    private static ApplicationContext ac=null;
   
    private ApplicaionContextUtil(){
       
    }
   
    static{
        ac=new ClassPathXmlApplicationContext("applicationContext.xml");
    }
    public static ApplicationContext getApplicationContext(){
        return ac;
    }
   
}


测试类可改为:

((UserService)ApplicaionContextUtil.getApplicationContext().getBean("userservice")).sayHello();

 

猜你喜欢

转载自chenzheng8975.iteye.com/blog/1595631