Spring要点总结


IOC :Inverse of control 控制反转
DI :Dependency Injection 依赖注入
---
Bean的生命范围scope属性:
1)singleton 单例
2)proptotype 每次创建新的对象
scope默认为singleton
----
集合注入(少用)

------

自动装配(IOC_AutoWire)
1)byName
2)byType
设置所有的bean都用同一种,可以使用beans的属性:default-autowire,

autowire="byTYPE"

-------

生命周期(IOC_Life_Cycle)
1)lazy-init 
2)init-method destroy-methd 不要和prototype一起用(否则destroy会失效,调用ctx.destroy时)

Bean生命周期

本来bean 在程序执行ctx=new ClassPathXmlApplicationContext("beans.xml");时就进行初始化了,若作了如下配置,则用到的时候才初始化。

<bean id="" lazy-init="true"/>

设置默认周期类型

<beans default-lazy-init="true">

<beans>

Lazy-init一般都不用,只有在应用启动时特别慢是采用。

------

IOC annotationXml方便

AOP xmlannotation强大

------

使用annotation:

修改xml文件,参考文档<context:annotation-config />

<aop:aspectj-autoproxy />


1)注入:

@Autowired

a)默认按类型by type
b)如果想用byName,使用@Qulifier
c)写在private field(第三种注入形式)(不建议,破坏封装)
d)如果写在set上,@qualifier需要写在参数上

如:

@Autowired
	public void setUserDAO(@Qualifier("u") UserDAO userDAO) {
		this.userDAO = userDAO;
	}

@Required表明必须注入
有点类似@override,写不写没关系,用于检测是否错误

@Resource(重要)
1)默认ByName,找不到的时候才用ByTYPE
2)可以指定特定名称

---------

2)组件Component:

<context:component-scan base-package="com.bjsxt"/> 

<!--扫描该目录,发现有@Component的放在容器里面成为资源-->

<property name="packagesToScan">

<list>

<value>com.bjsxt.model</value>

</list>

</property>

@Component @Service @Controller @Repository

a) 初始化的名字默认为类名首字母小写

b) 可以指定初始化bean的名字

-------

Scope在annotation的用法

@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
  // ...
}
------

@PostConstruct = init-method; 

@PreDestroy = destroy-method;

----------------------------------------------------------------------------------


AOP:Aspect-Oriented-Programming

面向切面编程

面向切面(用的地方:权限,日志,审查,效率,事务,异常)

Aspectj专门用来实现代理的框架

Spring使用了Aspect

是对面向对象的思维方式的有力补充

好处:可以动态的添加和删除在切面上的逻辑而不影响原来的执行代码

a)Filter
b)Struts2的interceptor

概念:
a)JoinPoint
b)PointCut(JoinPoint的集合)
c)Aspect(切面)
d)Advice(before ,after、、、、)
e)Target(加入的对象)
f)Weave

      1、join point(连接点):是程序执行中的一个精确执行点,例如类中的一个方法。它是一个抽象的概念,在实现AOP时,并不需要去定义一个join point。
      2、point cut(切入点):本质上是一个捕获连接点的结构。在AOP中,可以定义一个point cut,来捕获相关方法的调用。
      3、advice(通知):是point cut的执行代码,是执行“切面”的具体逻辑。
      4、aspect(切面):point cut和advice结合起来就是aspect,它类似于OOP中定义的一个类,但它代表的更多是对象间横向的关系。
      5、introduce(引入):为对象引入附加的方法或属性,从而达到修改对象结构的目的。有的AOP工具又将其称为mixin。
      6、AOP代理(AOP Proxy):AOP框架创建的对象,这个对象通常可以作为目标对象的替代品,而AOP代理提供比目标对象更加强大的功能。真实的情形是,当应用调用AOP代理的方法时,AOP代理会在自己的方法中回调目标对象的方法,从而完成应用的调用。关于AOP代理的典型例子就是Spring中的事务代理Bean。通常,目标Bean的方法不是事务性的,而AOP代理包含目标Bean的全部方法,而且这 些方法经过加强变成了事务性方法。简单地说,目标对象是蓝本,AOP代理是目标对象的加强,在目标对象的基础上,增加属性和方法,提供更强大的功能。
目标对象包含一系列切入点。切入点可以触发处理连接点集合。用户可以自己定义切入点,如使用正则表达式。AOP代理包装目标对象,在切入点处加入处理。在切入点加入的处理,使得目标对象的方法功能更强。Spring 默认使用JDK动态代理实现AOP代理,主要用于代理接口。也可以使用CGLIB代理。实现类的代理,而不是接口。如果业务对象没有实现接口,默认使用 CGLIB代理。但面向接口编程是良好的习惯,尽量不要面向具体类编程。因此,业务对象通常应实现一个或多个接口。
      7、目标对象(Target Object):包含一个连接点的对象,也被称为代理对象。
      8、 前置通知(Before advice):在某连接点(JoinPoint)之前执行的通知,但这个通知不能阻止连接点前的执行。ApplicationContext中在<aop:aspect>里面使用<aop:before>元素进行声明。 
      9、后通知(After advice) :当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。ApplicationContext中在<aop:aspect>里面使用<aop:after>元素进行声明。
      10、返回后通知(After return advice) :在某连接点正常完成后执行的通知,不包括抛出异常的情况。ApplicationContext中在<aop:aspect>里面使用<after-returning>元素进行声明。 
      11、环绕通知(Around advice) :包围一个连接点的通知,类似Web中Servlet规范中的Filter的doFilter方法。可以在方法的调用前后完成自定义的行为,也可以选择不执行。ApplicationContext中在<aop:aspect>里面使用<aop:around>元素进行声明。
      12、抛出异常后通知(After throwing advice) : 在方法抛出异常退出时执行的通知。 ApplicationContext中在<aop:aspect>里面使用<aop:after-throwing>元素进行声明。

annotation方式例子:

@Aspect
@Component
public class LogInterceptor {
	@Pointcut("execution(public * com.bjsxt.service..*.add(..))")
	public void myMethod(){};
	
	@Before("myMethod()")
	public void before() {
		System.out.println("method before");
	}
	
<span style="white-space:pre">	</span>@After("myMethod()")
	public void after() {
		System.out.println("method after");
	}
	
	@Around("myMethod()")
	public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("method around start");
		pjp.proceed();
		System.out.println("method around end");
	}
	
}

输出:

method before
method around start

user saved!
method around end
method after

xml方式例子:

<bean id="securityHandler" class="cn.ineeke.spring.SecurityHandler"/><!--切面,interceptor对象-->
<bean id="userDAO" class="cn.ineeke.spring.UserDAOImpl"/>  
<aop:config>  
<aop:aspect id="securityAspect" ref="securityHandler"><!--切面-->  
<aop:pointcut id="addMethod" expression="execution(* *(..))"/><!--切入点-->
<aop:before method="printSomthing" pointcut-ref="addMethod"/>  
</aop:aspect>  
</aop:config> 


常见的Annotation:

a)@Pointcut
b)@Before
c)@AfterReturning
d)@AfterThrowing
e)@After
f)@Around

对应相应的xml

-------------------------

声明式事务管理

<!-- from the file 'context.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:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="
     http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop.xsd">

  <!-- this is the service object that we want to make transactional -->
  <bean id="fooService" class="x.y.service.DefaultFooService"/>

  <!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) -->
  <tx:advice id="txAdvice" transaction-manager="txManager">
  <!-- the transactional semantics... -->
  <tx:attributes>
    <!-- all methods starting with 'get' are read-only -->
    <tx:method name="get*" read-only="true"/>
    <!-- other methods use the default transaction settings (see below) -->
    <tx:method name="*"/>
  </tx:attributes>
  </tx:advice>

  <!-- ensure that the above transactional advice runs for any execution
    of an operation defined by the FooService interface -->
  <aop:config>
  <aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.FooService.*(..))"/>
  <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
  </aop:config>

  <!-- don't forget the DataSource -->
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
  <property name="url" value="jdbc:oracle:thin:@rj-t42:1521:elvis"/>
  <property name="username" value="scott"/>
  <property name="password" value="tiger"/>
  </bean>

  <!-- similarly, don't forget the PlatformTransactionManager -->
  <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"/>
  </bean>

  <!-- other <bean/> definitions here -->

</beans>
---
<bean id="txManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<aop:config>
		<aop:pointcut id="bussinessService"
			expression="execution(public * com.bjsxt.service..*.*(..))" />
		<aop:advisor pointcut-ref="bussinessService"
			advice-ref="txAdvice" />
	</aop:config>

	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="getUser" read-only="true" />
			<tx:method name="add*" propagation="REQUIRED"/>
		</tx:attributes>
	</tx:advice>

------------------------------------------------------------


这个由Bean的作用域即配置的Scope属性有关,默认为sinlgleton类型,随着容器初始化而实例化,全局只有一个实例;prototype类型是在使用的时候实例化,每次实例化不同对象。还有request,session,global session类型。各有不同。具体可以参考spring手册中bean的作用域。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值