您的位置:首页 > 编程语言 > Java开发

spring

2016-05-22 20:42 253 查看
spring核心:ioc和aop

目前我只用到ioc,所以今天只介绍ioc

ioc:把New的对象交给spring管理,当要用这个对象时不用再new,只需要从spring中拿。。

IoC 不是一种技术,只是一种思想,一个重要的面向对象编程的法则,它能指导我们如何设计出松耦合、更优良的程序。传统应用程序都是由我们在类内部主动创建依赖对象,从而导致类与类之间高耦合,难于测试;有了IoC容器后,把创建和查找依赖对象的控制权交给了容器,由容器进行注入组合对象,所以对象与对象之间是松散耦合,这样也方便测试,利于功能复用,更重要的是使得程序的整个体系结构变得非常灵活。

需要spring.xml

<?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:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

           http://www.springframework.org/schema/context

           http://www.springframework.org/schema/context/spring-context-2.5.xsd">

           <context:annotation-config/>

        <context:component-scan base-package="cqupt"></context:component-scan>

</beans>

把注释了的全部加载,名字为首字母小写。。

<bean id="userDao" class="cqupt.dao.imp.UserDaoImp"></bean>    

       <bean id="userService" class="cqupt.service.imp.UserServiceImp">

        <property name="userDao"  ref="userDao"></property>

       </bean>

这种是手动加载和手动注入

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("springannotation.xml");

UserService userService=(UserService) ctx.getBean("userServiceImp");

加载文件并且,从中拿到这个bean

加载bean有两种:延迟加载(用的时候在加载)和初始化就加载

程序入口是web.xml

    <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>/WEB-INF/spring.xml</param-value>

    </context-param>

    <context-param>

    <param-name>webAppRootKey</param-name>

    <param-value>webapp.root3</param-value>

  </context-param>

    <context-param>

        <param-name>log4jConfigLocation</param-name>

        <param-value>/WEB-INF/log4j.properties</param-value>

    </context-param>

    <listener>

        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

    </listener>

    <listener>

        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

监听器会加载这些context
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  后台 框架 spring