初识Spring(小结)

1、初识Spring

位置:“一站式”框架,贯穿Web层(表现层)、Service层(业务逻辑层)、Dao层(持久层)

开发者使用Spring:开发Bean;配置Bean

因此Spring要做的就是:根据配置文件来创建Bean实例,并调用Bean实例的方法完成DI(依赖注入)

2、IOC

Spring要创建、管理Bean实例,这时IOC容器登场

3、DI

依赖注入作用:管理Bean之间的依赖关系(一种解耦方式,削弱硬编码耦合)

依赖:一个对象需要调用另一个对象的方法。传统做法:调用者主动创建被依赖对象,然后调用被依赖对象的方法,举个栗子(=.=)

//温馨提示,伪编码
//dao层接口
public interface IWorkDao{
    int insertObj(Object obj);
}

//实现类
public class WorkDao implement IWorkDao{   
    //..............
}

小问题:如果要将WorkDao改为WorkDaoImpl

//service层实现类
public WorkService implement IWorkService{

    //主动创建workDao对象
    private IWorkDao workDao = new WorkDao();
    
    //调用dao层方法
      @Override
            public int insertObj(Object obj) {
                return workDao.insert(obj);
        }
}

还得跑到service层修改,把new WorkDao() 改为new WorkDaoImpl(); 要是还有其他对象要调用这个dao对象的方法,一个一个找然后改,生无可恋(T_T),所以......

注入:通过第三方对另一个对象进行实例化

依赖注入方式:手动装配;自动装配

手动装配: 一般通过配置XML文件来完成关系装配,比如构造方法,setter方法

自动装配

                byType:按类型装配

                byName:按名称装配

注解注入:@Autowire 按类型自动注入 ;@Resource:按名称来自动注入

效果:Bean之间的低耦合,以配置文件组织在一起

4、注解

first tip!使用注解,必须引入context声明,在主配置文件中,扫描添加了注解的类

<context componet-scan base-package="添加注解的类的路径"></context>

注解小分队:

@Autowired,@Resource 自动装配依赖,默认是按照类型(byType)来装配

@Autowired可修饰setter方法、普通方法、实例变量和构造器等

@Resource(name="userDao"),自动按照名字来装配

@Qualifier,允许根据Bean的id来执行自动装配

@Scope("prototype") ,设置作用域,默认singleton

@Repository:dao层

@Service:service层

@Controller:web层

5、SpringAop

AOP就是希望将这些分散在各个业务逻辑代码中的相同代码,通过横向切割的方式抽取到一个独立的模块中,让业务逻辑类依然保存最初的单纯。

作用:性能监视、事务管理、安全检查、缓存,日志记录等

特点:SpringAOP使用纯Java实现,在运行期通过代理的方式向目标类织入增强代码

关键:代理   目标类   增强

底层实现:动态代理实现,基于JDK动态代理;基于Cglib动态代理

实现方式:

1、基于xml 配置,举个栗子(=.=),applicationContext.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 配置扫描添加了注解的类 -->
<!-- <context:component-scan base-package="com.lz"></context:component-scan> -->

    <!-- Spring容器实例化bean -->
    <bean id="userDao" class="com.lz.aop.Schema.dao.impl.UserDaoImpl" />

    <!-- 增强对象 -->
    <bean id="tx" class="com.lz.aop.Schema.transaction.TransactionManager" />

    <!-- 切面 -->
    <aop:config>
    <!-- 引入增强 -->
    <aop:aspect ref="tx">
    <!-- 切点 -->
    <!-- <aop:pointcut expression="execution(* add(..))" id="pc"/> -->
    <aop:pointcut expression="execution(* *(..))" id="pc"/>
    <!-- 织入 -->
    <aop:before method="begin" pointcut-ref="pc"/>
    <aop:after method="end" pointcut-ref="pc"/>
    </aop:aspect>

    </aop:config>

</beans>

测试类

public class Client {
    public static void main(String[] args) {
        
    ApplicationContext context = new    ClassPathXmlApplicationContext("applicationContext.xml");
    IUserDao userDao = (IUserDao) context.getBean("userDao");
    userDao.add();
    userDao.del();
    }
}

2、基于@AspcetJ注解(静态)

frist tip!导入com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

工作原理:

首先,在配置文件中引入aop命名空间,然后通过aop命名空间的<aop:aspectj-autoproxy/>自动为Spring容器中那些匹配@AspectJ切面的Bean创建代理,完成切面织入

@Aspect
public class MyAspectJ {

//前置增强
@Before("execution(* add(..))")
public void begin(){
System.out.println("begin...");
}

//后置增强
@AfterReturning("execution(* add(..))")
public void end(){
System.out.println("end...");
    }
}

环绕增强

@Aspect
public class MyAspectJ {

//环绕增强
@Around("execution(* add(..))")
public void around(ProceedingJoinPoint joinPoint){
try {
System.out.println("begin...");
joinPoint.proceed(); //放行
System.out.println("end...");
} catch (Throwable e) {
e.printStackTrace();
}
    }
}

抛出异常后增强

@Aspect
public class MyAspectJ {

//抛出异常后增强
@AfterThrowing("execution(* add(..))")
public void afterThrowing(){
System.out.println("抛出异常...");
    }
}

测试类

public class Client {
public static void main(String[] args) {
//目标对象
IUserDao userDao = new UserDaoImpl();

//AspectJ代理工厂
AspectJProxyFactory factory = new AspectJProxyFactory();
//通过工厂设置目标对象
factory.setTarget(userDao);
//添加切面类
factory.addAspect(MyAspectJ.class);
//创建代理类
IUserDao proxy = factory.getProxy();
proxy.add();
    }
}

6、Spring管理事务

常用的事务管理器:

DataSourceTransactionManager,jdbc开发时事务管理器

HibernateTransactionManager,hibernate开发时事务管理器

实现方式(个人积累),举个栗子(=.=)

1、自动化管理

//业务层
public class AccountServiceImpl implements IAccountService {
    //......业务逻辑代码
}

applicationContext.xml文件

<!-- 全自动化方式管理事务-->
<!-- 配置事务管理器,注入数据源 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理策略 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- name:方法
propagation:事务传播行为
isolation:事务隔离级别
-->
<tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!-- 将事务管理策略应用到哪些方法上 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.lz.service..*.*(..))"/>
</aop:config>

2、@Transactional注解

@Transactional
public class AccountServiceImpl implements IAccountService {
    //......业务逻辑代码
}

applicationContext.xml文件

<!-- 注解实现-->
<!-- 配置事务管理器,注入数据源 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<tx:annotation-driven transaction-manager="txManager" />

猜你喜欢

转载自blog.csdn.net/sinat_41333476/article/details/81142993