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

SSM笔记之spring

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

SSM笔记之spring

SSM笔记之spring
  • 1. IOC(控制反转)
    • 1.1 依赖注入(DI)
    • 1.2 scope
    • 1.3 基于注解的容器配置
    • 1.4 使用Java方式配置Spring
  • 2. AOP(面向切面)
    • 2.1 静态代理模式:
    • 2.2 动态代理
    • 2.3 使用Spring实现Aop
  • 3. spring整合MyBatis
    • 3.1 整合Mybatis的相关依赖
    • 3.2 步骤
  • 4.spring事务
    • 4.1 声明式事务

配置元数据的基本结构:



    

      
        
    

    
        
    

    


1. IOC(控制反转)

IOC:由spring容器去控制对象的创建
DI:自身对象中的内置对象是通过注入的方式进行创建

1.1 依赖注入(DI)

实例化容器

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

1. 构造器注入:



    



    




    

2. 属性注入(set注入)



    








    
        红楼梦
        西游记
        水浒传
        三国演义
    



    
        听歌
        敲代码
        看电影
    



    
        
        
    



    
        LOL
        BOB
        COC
    



    



    
        201293123
        sadjkfjl
        root
        123456
    


3. p、c命名空间





1.2 scope
  • 单例范围:scope=“singleton”, 一个对象

  • 原型范围:scope=“prototype”, 多个对象

  • web范围:session 、 application 、 request

1.3 基于注解的容器配置
  1. 基于xml配置文件的自动装配
 





 
  • byName: 会自动在容器上下文中查找,和自己对象set方法后面的值(id)对应的beanid!
  • byType: 会自动在容器上下文中查找,和自己对象属性类型(class)相同的bean
  1. 基于注解的自动装配
  • @Autowired : 自动装备通过类型。名字 优先byType 如果类型无法匹配就找和属性名一致的名字
    如果autowired不能唯一自动装配上属性,则需要通过@Qualifier(value=“xxx”)
  • @Resource : 自动装配通过名字。类型 优先通过byName,找不到就根据类型去找
  • @Qualifier:和@Autowired配合使用(指定名称来装配)
  • @Nullable : 字段标记了这个注解,说明这个字段可以为null;

Autowired先类型后名字

Resource先名字后类型

  1. @Component: 一个组件对象,放在类上,说明这个类被Spring管理了,就是bean!
    衍生注解
  2. @Repository: (数据库,仓库) 注解数据访问层(dao),功能与@Component相同
  3. @Service: 注解service层 ,功能与@Component相同
  4. @Controller: 注解controller层,功能与@Component相同
  5. @Value(“张三”) : 注入属性,相当于
1.4 使用Java方式配置Spring
  1. @Configuration+@Bean
//这个也会被spring容器托管,注册到容器中,因为它本身就是一个@Component,
//@Configuration代表这是一个配置类,就和我们之前看到的beans.xml
@Configuration
//@ComponentScan("com.xawl.pojo")
@Import(QinConfig2.class)  //导入其他配置类
public class QinConfig {

    //注册一个bean,就相当于我们之前写的一个bean标签,
    //这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User user(){
        return new User();//就是返回要注入到bean的对象!
    }
}

  1. @Configuration+@ComponentScan(“com.xawl.pojo”)+@Component
@Configuration
@ComponentScan("com.xawl.pojo")
public class QinConfig {

}
@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }

    //属性注入
    @Value("zhangsan")
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + ''' +
                '}';
    }
}

2. AOP(面向切面)

代理模式:

2.1 静态代理模式:

抽象角色 : 一般使用接口或者抽象类来实现

真实角色 : 被代理的角色

代理角色 : 代理真实角色 ; 代理真实角色后 , 一般会做一些附属的操作 .

客户 : 使用代理角色来进行一些操作 .

例子:

public class Client {
    public static void main(String[] args) {
        //房东要出租房子
        Host host = new Host();
        //代理,中介帮房东租房子,但是呢?代理角一般会有一些附属操作!
        Proxy proxy = new Proxy(host);
        //那你不用面对房东,直接找中介即可!
        proxy.rent();
    }
}
//租房
interface Rent {
    public void rent();
}
//房东
class Host  implements Rent{
    @Override
    public void rent() {
        System.out.println("房东要出租房子了!");
    }
}
//代理类
class Proxy {
    private Host host;
    public Proxy() {
    }

    public Proxy(Host host) {
        this.host = host;
    }

    public void rent() {
        seeHouse();
        host.rent();
        hetong();
        fare();
    }

    //看房
    public void seeHouse() {
        System.out.println("中介带你看房");
    }
    //签租赁合同
    public void hetong() {
        System.out.println("签租赁合同");
    }
    //收中介费
    public void  fare(){
        System.out.println("收中介费");
    }
}

  1. 静态代理的好处:
  • 可以使得我们的真实角色更加纯粹,不再去关注一些公共的事情。

  • 公共的业务由代理来完成 ,实现了业务的分工。

  • 公共业务发生扩展时变得更加集中和方便。

  1. 缺点:
  • 类多了,多了代理类,工作量变大了。开发效率降低
2.2 动态代理

动态代理的角色和静态代理的一样 .

动态代理的代理类是动态生成的 。 静态代理的代理类是我们提前写好的

动态代理分为两类 : 一类是基于接口动态代理 , 一类是基于类的动态代理

1. 基于接口的动态代理----JDK动态代理

2. 基于类的动态代理–cglib

现在用的比较多的是 javasist 来生成动态代理

public class  Client {
    public static void main(String[] args) {
        //真是角色
        Host host = new Host();
        //代理角色: 现在没有
        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        //通过调用程序处理角色来处理我们要调用的接口对象!
        pih.setRent(host);
        Rent proxy = (Rent) pih.getProxy();//这里的proxy就是动态生成的,我们并没有写·
        proxy.rent();
    }
}
//租房
interface Rent {
    public void rent();
}
//房东
class Host  implements Rent {

    @Override
    public void rent() {
        System.out.println("房东要出租房子了!");
    }
}
//等我们会用这个类,自动生成代理类!
class ProxyInvocationHandler implements InvocationHandler {
    //被代理的接口
    private Rent rent;
    public void setRent(Rent rent){
        this.rent = rent;
    }
    
    // 生成得到代理类
    public Object getProxy(){
       return  Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
    }
    @Override
    //处理代理实例,并返回结果
    //proxy:代理对象
    //method:调用的方法
    //args:方法中的参数
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        seeHouse();
        //动态代理的本质就是反射,用反射机制来实现!
        Object result = method.invoke(rent,args);
        fare();
        return result;
    }

    public void seeHouse(){
        System.out.println("中介带看房子");
    }

    public void fare(){
        System.out.println("收中介费");
    }
}
2.3 使用Spring实现Aop
  1. 方式一: 使用Spring的API接口 [主要SpringAPI接口实现]
public class AfterLog implements AfterReturningAdvice {
    //returnValue: 返回值
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为:"+returnValue);
    }
}

public class Log implements MethodBeforeAdvice {
    //method: 要执行的目标对象的方法
    //args:参数
    //target:目标对象
    @Override
    public void before(Method method, Object[] objects, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了 ");
    }
}


    
    
    
    
    

  1. 方式二: 自定义来实现AOP [主要是切面定义]
public class DiyPointCut {
    public void before(){
        System.out.println("========方法执行前=======");
    }
    public void after(){
        System.out.println("========方法执行后=======");
    }
}




    
    
        
        
        
        
        
    

  1. 方式三: 使用注解实现
//使用注解方式实现AOP
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* com.xawl.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("=======方法执行前=======");
    }
    @After("execution(* com.xawl.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("=======方法执行后=======");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入点;
    @Around("execution(* com.xawl.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");

        Signature signature = jp.getSignature();//获得签名
        System.out.println("signature:"+signature);
        //执行方法
        Object proceed = jp.proceed();
        System.out.println("环绕后");

        System.out.println(proceed );
    }
}
3. spring整合MyBatis 3.1 整合Mybatis的相关依赖

  
    junit
    junit
    4.12
    test
  
  
    mysql
    mysql-connector-java
    8.0.26
  
  
    org.mybatis
    mybatis
    3.5.2
  
  
    org.springframework
    spring-webmvc
    5.2.0.RELEASE
  
  
  
    org.springframework
    spring-jdbc
    5.2.0.RELEASE
  
  
    org.aspectj
    aspectjweaver
    1.9.4
  
  
    org.mybatis
    mybatis-spring
    2.0.2
  
  
    org.projectlombok
    lombok
    1.18.22
    provided
  




  
    src/main/java
    
      **/*.xml
    
    true
  


3.2 步骤
  1. 导入依赖
  2. 编写实体类
@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}
  1. 编写配置文件
    applicationContext.xml


    
    
        
    

mybatis-config.xml




  
    
  

  
 

spring-dao.xml:


    
    
    
        
        
        
        
    
    
    
        
        
        
        
    

    
    
        
        
    



  1. 编写mapper
    UserMapper.java:
public interface UserMapper {
    List select();
}

UserMapper.xml:




    

  1. 编写mapper的实现类
public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSession;

    public void setSessionTemplate(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }
    @Override
    public List select() {
        return sqlSession.getMapper(UserMapper.class).select();
    }
}

  1. 测试
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        List select = userMapper.select();
        for (User user : select) {
            System.out.println(user);
        }
    }
}

运行结果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lDfNEZz2-1652594639362)(img_1.png)]

4.spring事务 4.1 声明式事务


	
	    
		
		
		
	



    
    
    

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

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

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