Spring基础的学习(一)

来源:互联网 发布:linux自启动脚本 编辑:程序博客网 时间:2024/06/05 07:40

对spring学了也有一段时间了,开始可能了解大致怎么用,但是原理方面还是不太清楚,之后上班公司也有用到,但是基本上都是别人配置好,只需要我们在此基础上做开发,所以有很多东西都不是太清楚了,只能在网上大致找一下文章,哪里不清楚再继续查,再此也做点记录,以后不清楚了可以看看,不用到处搜寻答案了这里也是看了网上的资料简单的总结了下怎么用!

1.目前来讲Spring主要是了解IOC(依赖注入)和AOP(面向切面),这也是他的核心部分了,那么具体如何实现,可能我们需要去看一下源码,同时对于java 的反射与设计模式都应该有一些了解,想AOP就是典型的动态代理来实现的。

实现IoC通常有三种方式:
  1)利用接口或者继承,一般以接口较多。这种实现方式和我们平时提到的lazy load有异曲同工之妙。
    <bean id="userDaoImpl" class = "com.spring.ioc.UserDaoImpl"/>   静态方法获取对象:<pre name="code" class="html">   <bean id="userDaoImpl2" class = "com.spring.ioc.UserDaoFactory" factory-method = "getUserDao"/>
    其中包括工厂模式的实现:
   <bean id="factory" class="com.spring.ioc.UserDaoFactory2"/>   <bean id="userDaoImpl3" factory-bean="factory" factory-method="getUserDao"/>
  2)构造函数注入。
       ①根据引用
     <bean id="service" class="service.impl.UserServiceImpl">           <constructor-arg ref="jdbcdao"></constructor-arg>     </bean>

       ②根据索引

       <!--类构造器实例化-->        <bean id="formaterBean" class="com.neusoft.test.spring.impl.UpperFormat" >        </bean>        <!--属性注入-->        <bean id="textPrinter" class="com.neusoft.test.spring.impl.TextPrinter">            <constructor-arg index="0">              <ref bean="formaterBean"/>           </constructor-arg>          <!--基本注入-->         <constructor-arg index="1" value="str" />       </bean>  

  3)属性注入。
   <bean id="userService" class="sample.spring.ioc.UserServiceBean">    <property name="userID" value="1"/>    <property name="userName" value="张三"/>    <property name="userDao" ref="userDaoImpl"/>    <property name="hobbies">        <list>            <value>羽毛球</value>            <value>看电影</value>            <value>弹吉他</value>        </list>    </property>    <property name="scores">        <map>            <entry key="数据结构" value="90"/>            <entry key="编译原理" value="85"/>            <entry key="离散数学" value="82"/>        </map>    </property></bean>

AOP:Spring框架集合了ProxyFactory和Cglib两种方式来实现AOP。

   因为java的动态代理必须依赖于接口,如果没有接口的情况下是可以通过Cglib来实现的,关于ProxyFactory的xml配置如下

<bean id="myInterceptor2" class="come.spring.aop.MyInterceptor2"/><aop:config>    <aop:aspect id="asp" ref="myInterceptor2">        <aop:pointcut id="anyMethod" expression="execution (* com.spring.aop.*.*(..))"/>        <aop:before pointcut-ref="anyMethod" method="before"/>        <aop:after pointcut-ref="anyMethod" method="after"/>        <aop:around pointcut-ref="anyMethod" method="around"/>        <aop:after-returning pointcut-ref="anyMethod" method="afterReturning" returning="result"/>        <aop:after-throwing pointcut-ref="anyMethod" method="afterThrowing" throwing="e"/>    </aop:aspect></aop:config>







0 0
原创粉丝点击