2020.06-Study_update.1

week 6.1-6.7

- Study-update
-Mon spring c命名空间和p命名空间,@PropertiesSource注解
-Tue 代理模式的好处
-Wes 动态代理复习,aop实现方式,
-Thue aop注解方式,lombok@Data注解,mybatis_spring整合.aop声明式事务
-Fri SpringMvc,/和/*的区别
-Sat SpringMVC注解
-Sun -

6.1 Monday

@PropertiesSource("classpath:)
classpath表示类路径下的文件
使用“${}”读取

6.2 Tuesday

代理模式的好处
可以使真实的角色的操作更加纯粹,不用去关心其他公共业务。
公共业务交给了代理角色,更好的分工。
公共业务需要修改时,能更好的管理。

spring整合junit

Spring整合Junit的配置
1,导入spring整合junit的jar(坐标)
2,使用junit提供的一个注解把原有的main方法替换了,替换成spring提供的
@Runwith
3,告知spring运行器,spring和ioc创建是基于xml还是注解,还有位置。
@ContextConfiguration
locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
classes:指定注解类所在地位置。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class Test {
//    private AnnotationConfigApplicationContext context;
    @Autowired
    private IAccountService accountService;
//
//    @Before
//    public void init(){
//        context = new AnnotationConfigApplicationContext(SpringConfig.class);
//        accountService = context.getBean(AccountServiceImpl.class);
//    }
    @org.junit.Test
    public void testFindAll() {
//        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        List<Account> accounts = accountService.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }

6.3 Wesday

/**
 * @author lzr
 * @date 2020/6/3 08:15:40
 * @description
 */
//用这个类动态生成代理类
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口
    private Rent rent;
    //传入被对象
    public void setRent(Rent rent) {
        this.rent = rent;
    }

    //生成得到代理类
    public Object getProxy(){
       return Proxy.newProxyInstance(ProxyInvocationHandler.class.getClassLoader(),rent.getClass().getInterfaces(),this);
    }

    //处理代理实例,并返回结果
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result=method.invoke(rent,args);
        return result;
    }
}

aop实现方法一

    <context:component-scan base-package="com.maaoooo"/>
<!--    方法一
        使用原生API接口
 -->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.maaoooo.service.UserServiceImpl.*(..))"/>
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

/**
 * @author lzr
 * @date 2020/6/3 09:30:42
 * @description
 */
@Component
public class AfterLog implements AfterReturningAdvice {

    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+"返回了"+returnValue);
    }
}


/**
 * @author lzr
 * @date 2020/6/3 09:22:49
 * @description
 */
@Component
public class Log implements MethodBeforeAdvice {
    //method:要执行的目标方法
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了.");
    }
}


/**
 * @author lzr
 * @date 2020/6/3 16:56:27
 * @description
 */
@Repository
public class UserServiceImpl implements UserService{
    public void add() {
        System.out.println("增加用户");
    }

    public void delete() {
        System.out.println("删除用户");
    }

    public void update() {
        System.out.println("更新用户");
    }

    public void select() {
        System.out.println("查询用户");
    }
}

6.4 Thuesday

    <aop:aspectj-autoproxy proxy-target-class="true"/>
<!--    当 proxy-target-classfalse时,使用jdk. true为cglib 默认为false.-->

lombok
@Data
为实体类提供getset方法和toString()等方法。
1、下安装lombok插件
2020.06-Study_update.1_第1张图片
2、重启idea
3、在maven库中添加依赖

org.projectlombok
lombok
1.16.10

4、在实体类上添加@Data注解即可生效
————————————————
原文链接:https://blog.csdn.net/pzq915981048/article/details/99086924

mybatis_spring整合

1.编写数据源配置

<!--    datasource-->
    <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/webtest"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

2.sqlSessionFactory

<!--    SqlsessionFactroy-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="com/maaoooo/mapper/*.xml"/>
    </bean>

3.sqlSessionTemplate

<!--    sqlSessionTemplate-->
    <bean class="org.mybatis.spring.SqlSessionTemplate" id="sessionTemplate">
        <constructor-arg ref="sessionFactory"/>
    </bean>

4.给接口加实现类

/**
 * @author lzr
 * @date 2020/6/4 11:58:24
 * @description
 */
public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    public List<User> selectAllUser() {
        return sqlSessionTemplate.getMapper(UserMapper.class).selectAllUser();
    }
}

5.测试

/**
 * @author lzr
 * @date 2020/6/4 14:10:23
 * @description
 */
public class Test {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UserMapperImpl bean = context.getBean(UserMapperImpl.class);
        List<User> users = bean.selectAllUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
}
------------------------------------------------------
User(id=3, username=小刘, password=123)
User(id=4, username=xiaoliu, password=123)
User(id=5, username=123, password=123)
User(id=7, username=BKB, password=wudi)
User(id=13, username=aaa, password=bbb)
User(id=14, username=aaa, password=bbb)
User(id=17, username=wudi, password=aaaaaa)
User(id=18, username=aaa, password=bbb)
User(id=19, username=aaa, password=bbb)
User(id=20, username=wudi, password=aaaaaa)

另外一种方法
实现类继承SqlSessionDaoSupport
可以直接调用getSqlSession

/**
 * @author lzr
 * @date 2020/6/4 11:58:24
 * @description
 */
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {

    public List<User> selectAllUser() {
        return getSqlSession().getMapper(UserMapper.class).selectAllUser();
    }
}

配置得改传入 SessionFactory

<!--    sqlSessionTemplate-->
    <bean class="org.mybatis.spring.SqlSessionTemplate" id="sessionTemplate">
        <constructor-arg ref="sessionFactory"/>
    </bean>

aop声明式事务

<!--    配置事务管理器-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    配置aop事务-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--        给哪些方法配置事务-->
<!--        配置事务的传播特性-->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

<!--    配置事务切入-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.maaoooo.mapper.UserMapperImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
    </aop:config>

6.5 Friday

SpringMvc要做的
1.将url映射到java类或java类的方法
2。封装用户提交的数据
3.处理请求,调用相关业务处理,封装响应的数据
4。将响应的数据在表现层进行渲染

为什么要学spring
1.轻量级
2.基于请求响应的mvc框架,高效
3.与spring兼容性好/
4.约定优于配置
5.功能强大

HelloSpringMvc原理

1.新建一个项目
2.添加依赖

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.27.RELEASE</version>
    </dependency>
</dependencies>

3.配置web.xml,注册DispatcherServlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc-servlet.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
</web-app>

4.编写SpringMvc配置 名称:springmvc-servlet.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

5.添加处理映射器

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

6.添加处理器适配器

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

7.添加视图解析器

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

8.编写要操作业务Controller,要么实现Controller接口,要么增加注解;需要返回一个ModelAndView,装数据,封视图。

/**
 * @author lzr
 * @date 2020/6/5 11:04:26
 * @description
 */
public class HelloController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //模型和视图
        ModelAndView mv=new ModelAndView();
        //封装对象,放在modelAndView中
        mv.addObject("msg","HelloSpringMvc!");
        //封装要转跳的视图,放在modelAndView中
        mv.setViewName("hello");
        return mv;
    }
}

9.将自己的类交给容器管理。

<bean class="com.maaoooo.controller.HelloController" id="/hello"/>

10.写要跳转的jsp页面,显示ModelAndView存放的数据,及页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/6/5
  Time: 11:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${msg}
</body>
</html>

2020.06-Study_update.1_第2张图片
总体流程,请求先被DispatcherServlet处理,然后经过处理映射器找到相应的处理适配器,跳转到相应的Controller进行业务处理,然后返回一个ModelAndView,通过视图解析器找到相应的页面渲染出视图。

/和/*的区别
/只匹配所有的请求,不会匹配jsp
/*匹配所有的请求 包括jsp

6.6 Satday

HelloSpringMvc注解

1.配置DispatcherServlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc-servlet.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
</web-app>

2.配置注解扫描,不处理静态资源,和配置annotation-driven

<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
   http://www.springframework.org/schema/tx 
   http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--    配置注解扫描-->
    <context:component-scan base-package="com.maaoooo.controller"/>
<!--    让springmvc不处理静态资源-->
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

<!--    视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3.配置相应的Controller

package com.maaoooo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lzr
 * @date 2020/6/6 10:01:42
 * @description
 */
@Controller
@RequestMapping("/web")//多级访问路径
//@RestController json
public class HelloController {
//决定了哪个访问路径会被该controller处理
    @RequestMapping("/hello")
    public String hello(Model model){
        //封装数据
    model.addAttribute("msg","HelloSpringMvc!");
        return "hello";//会被视图解析器处理
    }
}

4.配置相应响应页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/6/6
  Time: 10:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${msg}
</body>
</html>

5.配置tomcat。测试

你可能感兴趣的:(笔记)