栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

框架之初步了解Spring(二)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

框架之初步了解Spring(二)

初步学习Spring
  • 一、Spring注解开发
    • 1.1 Spring常用注解
    • 1.2 Sring替代配置相关注解
  • 二、基于注解的AOP开发
    • 2.1 使用注解替换
    • 2.2 切点表达式
    • 2.3 通知类型
    • 2.4 环绕通知
    • 2.5 纯注解配置
  • 三、Spring的事务
    • 3.1 事务相关API
      • 3.1.1 PlatformTransactionManager
      • 3.1.2 TransactionDefinition
      • 3.1.3 TransactionStatus
    • 3.2 通过注解的方式使用声明式事务
  • 四、Spring集成web环境
    • 4.1 创建web工程
    • 4.2 自定义监听器和工具类

一、Spring注解开发

Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。

1.1 Spring常用注解
  1. 替代的常用注解
- @Component:相当于

- @Repository:在持久层使用注解

- @Service:在业务层使用注解

- @Controller:在表现层使用注解
  1. DI依赖注入的相关注解
- @Autowired :相当于 app.getBean(class类型)  代替此标签 

- @Qualifie  :需要跟@Autowired组合使用,来指定同类型下某个具体的id

- @Resource  :由jdk自带,相当于 @Autowired + @Qualifie
注解说明
@Autowired根据类型查找
@Autowired @Qualifie(“xxx”)根据类型 + id查找
@Resource(name=“xxx”)直接根据id查找
  1. bean属性相关注解
- @Scope("prototype"):相当于 单例/多例

- @PostConstruct:相当于对象初始化时触发的方法

- @PreDestroy:相当于对象销毁前触发的方法
  1. 参数注入
- @Value :相当于  
  1. 示例
@Service
@Scope("prototype")
public class AccountServiceImpl implements AccountService {
	
	@Value("${jdbc.driver}")
	private String driverCalssName;
	
    
    @Resource(name = "accountDaoImpl")
    private AccountDao accountDao;


    @Override
    public void save() {
        accountDao.save();
    }

    @PostConstruct
    public void init() {
        System.out.println("创建了");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("销毁了");
    }
}
1.2 Sring替代配置相关注解
- @Configuration:相当于applicationContext.xml

- @ComponentScan:相当于  

- @PropertySource:相当于 

- @Bean:将第三方类(对象)交给ioc容器

- @Import:相当于 
  1. Spring配置类
@Configuration // applicationContext.xml
@PropertySource("classpath:jdbc.properties")// 
public class SpringConfig {

}
  1. 配置类模块化

主配置类:

@Configuration
@Import(DataSourceConfig.class) // 
public class SpringConfig{

	//创建第三方对象
	@Bean("queryRunner")
	public QueryRunner queryRunner(DataSource){ //方法形参位置会自动从ioc容器获取对象实例,完成注入
		return new QueryRunner(dataSource);
	}
}

从配置类:

public class DataSourceConfig {

    @Value("${jdbc.driver}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    // 创建连接池(第三方对象)
    @Bean("dataSource")
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}
二、基于注解的AOP开发 2.1 使用注解替换
  1. 删除xml的aop配置,开启注解的aop支持




    
    


    
    

  1. 将通知标注为切面类
@Component
@Aspect // 标注为切面类 
public class TransactionManager {

    @Before("execution(* com.baidu.service..*.*(..))") // 
    public void before() {
        System.out.println("前置通知【开启事务】");
    }
}
2.2 切点表达式
@Component
@Aspect // 标注为切面类 
public class TransactionManager {

    //   
    @Pointcut("execution(* com.baidu.service..*.*(..))")
    public void myPointcut() {
    }

    @Before("myPointcut()") // 
    public void before() {
        System.out.println("前置通知【开启事务】");
    }
}
2.3 通知类型
名称标签说明
前置通知@Before在切入点方法之前执行
后置通知@AfterReturning在切入点方法正常运行之后执行
异常通知@AfterThrowing在切点方法发生异常的时候执行
最终通知@After无论切入点方法执行时是否有异常,都会执行
@Component
@Aspect // 标注为切面类 
public class TransactionManager {

    //   
    @Pointcut("execution(* com.baidu.service..*.*(..))")
    public void myPointcut() {
    }

    @Before("myPointcut()") // 
    public void before() {
        System.out.println("前置通知【开启事务】");
    }

    @AfterReturning("myPointcut()")
    public void afterReturning() {
        System.out.println("后置通知【事务提交】");
    }

    @AfterThrowing("myPointcut()")
    public void afterThrowing() {
        System.out.println("异常通知【事务回滚】");
    }

    @After("myPointcut()")
    public void after() {
        System.out.println("最终通知【释放资源】");
    }
}

在注解中同时使用四大通知,执行顺序:

@Before -> @After -> @AfterRunning(如果有异常@AfterThrowing)

在开发当中尽量不要使用注解的四大通知,特殊场景推荐使用:环绕通知

2.4 环绕通知
名称标签说明
环绕通知@Around可以灵活实现四大通知的所有效果
// 环绕通知 Proceeding + JoinPoint
@Around("myPointcut()")
public void around(ProceedingJoinPoint pjp) {
    try {
        this.before();
        // 调用切点(目标对象的方法)原有的功能
        pjp.proceed();
        this.afterReturning();
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        this.afterThrowing();
    } finally {
        this.after();
    }
}
2.5 纯注解配置
@Configuration// applicationContext.xml
@ComponentScan("com.baidu")//  
@EnableAspectJAutoProxy// 
public class SpringConfig {
}
@RunWith(SpringRunner.class)
// @ContextConfiguration(locations = "classpath:applicationContext.xml")
@ContextConfiguration(classes = SpringConfig.class)
public class AccountTest {

    @Autowired
    private AccountService accountService; // 已经是代理对象了

    @Test
    public void test01() throws Exception {
        accountService.transfer();
        // accountService.findAll();
    }
}
三、Spring的事务

Spring的事务控制可以分为编程式事务控制和声明式事务控制。

  • 编程式事务:业务代码和事务代码放在一起书写,它的耦合性太高,开发中不使用
  • 声明式事务:将事务代码和业务代码隔离开发, 然后通过一段配置让他们组装运行, 最后达到事务控制的目的

声明式事务是通过AOP原理实现的。

3.1 事务相关API 3.1.1 PlatformTransactionManager

PlatformTransactionManager:Spring事务管理器的顶级接口,里面提供了常用的操作事务的方法。

- TransactionStatus getTransaction(TransactionDefinition definition);
	功能:获取事务的状态信息

- void commit(TransactionStatus status);
	功能:提交事务

- void rollback(TransactionStatus status);
	功能:回滚事务

如果要查看事务管理器实现类,需要导入坐标



    org.springframework
    spring-orm
    5.1.5.RELEASE

  1. JpaTransactionManager:是根据jpa规范实现的持久层框架提供的事务管理器实现:spring-data-jpa框架

  2. DataSourceTransactionManager:根据连接池规范实现的持久层框架提供的事务管理器实现:mybatis、jdbcTemplate

  3. HibernateTransactionManager:是hibernate框架特有的事务管理器实现

3.1.2 TransactionDefinition

TransactionDefinition:Spring事务定义参数的接口,比如定义:事务隔离级别、事务传播行为等等

  1. 事务隔离级别
隔离级别含义
DEFAULT使用数据库默认的隔离级别
READ_UNCOMMITTED可能导致脏读、幻读或不可重复读
READ_COMMITTED(Oracle 默认级别)可防止脏读,但幻读和不可重复读仍可能会发生
REPEATABLE_READ(MySQL默认级别)可防止脏读和不可重复读,但幻读仍可能发生
SERIALIZABLE确保不发生脏读、不可重复读和幻影读
  1. 事务传播行为

事务传播行为指的是:事务的传播或者事务的行为,比如说多个方法之间调用运行,是否共享同一个事务还是开启一个新事物呢,这个是可以设置的。

关键字描述
REQUIRED【默认】如果有事务在运行,当前方法将会在该事务中运行。否则,会启动一个新的事务,并在自己的事务中运行
SUPPORTS如果有事务在运行,当前方法将会在该事务中运行。否则,它可以不在一个事务中运行
MANDATORY表示该方法必须在事务中运行,如果当前事务不存在,则会抛出一个异常
REQUERS_NEW表示当前方法必须运行在它自己的事务中。一个新的事务将被启动。如果存在当前事务,在该方法执行期间,当前事务会被挂起
NOT_SUPPORTED表示该方法不应该运行在事务中。如果存在当前事务,在该方法运行期间,当前事务将被挂起
NEVER表示该方法不应该运行在事务中。如果当前正有一个事务在运行,则会抛出异常
NESTED表示如果当前已经存在一个事务,那么该方法将会在嵌套事务中运行。嵌套的事务可以独立于当前事务进行单独地提交或回滚。如果当前事务不存在,那么其行为与REQUIRED一样
  1. 是否只读
关键字描述
read-only只读事务(增 删 改不能使用,只能查询使用)
  1. 超时时间
关键字描述
timeout默认值是-1,没有超时限制。如果有,以秒为单位进行设置
3.1.3 TransactionStatus

TransactionStatus:获取spring当前事务运行的状态,根据定义的参数,会返回事务实时状态,从而进行提交/回滚等操作

3.2 通过注解的方式使用声明式事务
@Service
@Transactional  //
public class AccountServiceImpl implements AccountService{

	@Autowired
	private AccountDao accountDao;

	@Transactional    // 指定当前方法进行事务控制,优先级高于类中注解配置
	@Override
	public void transfer(){
		System.println.out("转账成功");
	}
}
四、Spring集成web环境 4.1 创建web工程

    org.springframework
    spring-web
    5.1.5.RELEASE

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = app.getBean(UserService.class);
        userService.save();

        response.getWriter().write("ok");
    }

}

存在的问题:

  • 用户每次发送请求,都会调用doXX方法,里面创建了Spring容器,使用完毕后又销毁了,浪费性能

解决方案:

  • Spring容器在项目中只初始化一次即可
4.2 自定义监听器和工具类

tomcat启动并创建ServletContext对象时会触发ServletContextListener监听器的监听方法,因此可以在此方法内去创建Spring的容器对象,并存储到ServletContext域中,那么所有的servlet就可以直接获取spring的容器对象了。

MyContextLoaderListener

public class MyContextLoaderListener implements ServletContextListener {

    // 监听创建
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 获取域对象
        ServletContext servletContext = sce.getServletContext();
        // 读取全局配置参数
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
        // 创建spring环境
        ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
        // 将spring存储到域对象中
        servletContext.setAttribute("app", app);
    }

    // 监听销毁
    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}

web.xml




    
    
        contextConfigLocation
        beans.xml
    


    
    
        com.baidu.web.listener.MyContextLoaderListener
    

MyWebApplicationContextUtils

public class MyWebApplicationContextUtils {

    public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
        return (ApplicationContext) servletContext.getAttribute("app");
    }
}

修改UserServlet

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       
        ApplicationContext app = MyWebApplicationContextUtils.getWebApplicationContext(getServletContext());
        UserService userService = app.getBean(UserService.class);
        userService.save();

        response.getWriter().write("ok");
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/891306.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号