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

Spring学习笔记

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

Spring学习笔记

1. IOC创建对象 1.HelloSpring环境搭建(第一个Spring程序)

1.maven下载pom依赖

2.创建xml配置文件



​
    
        
        
​
    
​
​

3.创建实体类

4.测试

   
//引入上下文
ApplicationContext context = new ClassPathXmlApplicationContext( "BeanSpring.xml");
//获取对象
        HelloSpring bean = (HelloSpring)context.getBean("hello");

2. 有参构造bean的xml使用 利用下标


    
        
        
​
    
​
​
传入引用对象


    
        
​
​
    
​
​
使用构造参数名字


    
        
​
​
    
​
​
2. Spring配置文件解析 别名
    
        
    

    
配置

        
import
  

    
    
3. 依赖注入 3.1 构造器注入
 
        
    
3.2 Set注入

依赖注入:依赖于容器,将bean对象属性值注入到对象中(就是Spring容器代理操作对象)

环境搭建

1. 测试对象引用bean创建

package com.xiaofeng.pojo;

public class Address {
    private String address;

    public void setAddress(String address) {
        this.address = address;
    }

    public String getAddress() {
        return address;
    }

    @Override
    public String toString() {
        return "Address{" +
                "address='" + address + ''' +
                '}';
    }
}

2. 真是测试对象

    private String name;
    private Address address;
    private String[] books;
    private List hobbys;
    private Map card;
    private Set games;
    private String wife;
    private Properties info;

3. xml文件创建




    

4. 测试类

import com.xiaofeng.pojo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    @org.junit.Test
    public void Test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
        Student student = (Student)context.getBean("student");
        String name = student.getName();
        System.out.println(name);
    }
}

5. 完善set映射


       
       
       
       
           
           
               悲惨世界
               天狗
           
       
       
           
           
               
               
           
       
       
           
           
               lol
               阴阳师
           
       
       
           
           
               看电影
               听歌
           
       
       
           
           
               0000
               111
           
       
       
           
           
       
   

6. 扩展p c标签快捷注入

xmlns:p="http://www.springframework.org/schema/p"


 
 




xmlns:c="http://www.springframework.org/schema/c"








 
4. 自动装配 4.1 byName自动装配
 
    

    
    

小结:需要确保bean id 的唯一值

4.2 byType自动装配
 
    

    
    

小结:需要确保type的唯一

4.3 使用注解自动装配 4.3.1 配置环境

导入context约束 开启注解支持




    

4.3.2 使用@Autowired标记ref属性自动装配
  @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;

注意:需要装配的对象需要在容器中都已注册


    
    
    
    

 @Autowired
    @Qualifier("cat1")
    private Cat cat;
//此注解通过byType自动装配,如果存在相同Type 则通过byName  如果byName也查找不到  则可使用 @Qualifier指定name
 @Autowired
    @Nullable
    private Cat cat;
//使用Nullable 标记属性可以为空

4.3.2.1 小结:

@Autowired 此注解通过byType自动装配,如果存在相同Type 则通过byName

@Qualifier("") 如果byName也查找不到 则可使用 @Qualifier指定name

@Nullable 使用Nullable 标记属性可以为空

@Resource 和@Autowired差不多,但可直接传入参数选则填充对象,不用借助@Qualifier 优先通过名字然后是类型 jdk特有的注解

5. 使用注解开发
  1. 导入AOP包

  2. 开启注解支持




    
    

  1. 使用@Component直接注册bean 等价于 id默认小写

    @Component
    public class Person {
        //vale可以指定直接值,ref值用@Autowired自动装配
        @Value("段晓风")
        private String name;
    }
  2. 注解衍生

    @value("") 指定属性直接值

    @Component 使用此注解相当于在xml中注册bean

    @Component的衍生注解,按照MVC三层架构分层,将其注入到Spring中:

    ` Dao @Service

    `Service @Repository

    `Controller @Controller

  3. 自动装配注解

    @Autowired 此注解通过byType自动装配,如果存在相同Type 则通过byName

    @Qualifier("") 如果byName也查找不到 则可使用 @Qualifier指定name

    @Nullable 使用Nullable 标记属性可以为空

    @Resource 和@Autowired差不多,但可直接传入参数选则填充对象,不用借助@Qualifier 优先通过名字然后是类型 jdk特有的注解

  4. @Scope注解作用域

    @Scope("prototype")
    public class Person {
        @Value("段晓风")
        private String name;
    }

小结:

xml用于象管理

注解只负责注入属性

使用注解,一定要开启注解支持

 
    

复杂对象管理 建议还是使用xml

6. 使用纯代码配置Spring注解 6.1开头总节

@Configuation等价于

@Bean等价于

@ComponentScan等价于

5.2 @Configuation+@Bean方式注入
@Configuration

public class Config {
    @Bean
    public User getUser(){
        return new User();
    }

5.3 @ComponentScan(basePackages = "")+@Component
@Component
public class User {
    public User(){
        System.out.println("实例被创建了");
    }
    @Value("段晓风")
    private String name;

}


@ComponentScan(basePackages = "com.xiaofeng.pojo")
public class Config {

}
5.4 @import(Config2.class)导入其他配置类 5.5 在@configuration中引入spring的xml配置文件
@importResource("classpath:applicationContext-configuration.xml")
7. 动态代理 7.1 InvocationHandler

调用处理器

只有一个invoke方法,生成的代理类实例实际是调用了这个方法

7.2 Proxy

代理类

7.3 实现步骤

1.实现InvocationHandler接口

public class InvocationHandlerImpl implements InvocationHandler 

2.获取代理类实例

 public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),demo.getClass().getInterfaces(),this);
    }

通过传入实际代理对象的加载器 接口列表 调用处理器实例 来创建代理类实例

3.测试

public class Test {
    public static void main(String[] args) {
        Host host = new Host();
        InvocationHandlerImpl handler = new InvocationHandlerImpl(host);
        Rent proxy = (Rent)handler.getProxy();
        String rent = proxy.rent();
        System.out.println(rent);
    }
}

完整代码

package com.xiaofeng.Demo1;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class InvocationHandlerImpl implements InvocationHandler {
    private Object demo;
    public InvocationHandlerImpl(Object demo){
        this.demo=demo;
    }
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),demo.getClass().getInterfaces(),this);
    }
    //这里是实际调用方法,当生成的proxy调用方法时,会通过反射调用该方法,method调用的代理对象的方法,args时参数列表
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(demo, args);
        String result1="实际调用了这里的方法";
        System.out.println(result1);
        return result;
    }
}

为什么会自动调用InvocationHandlerImpl的invoke方法? 因为JDK生成的最终真正的代理类,它继承自Proxy并实现了我们定义的Rent接口, 在实现Rent接口方法的内部,通过反射调用了InvocationHandlerImpl的invoke方法。

通过分析代码可以看出Java 动态代理,具体有如下四步骤:

通过实现 InvocationHandler 接口创建自己的调用处理器; 通过为 Proxy 类指定 ClassLoader 对象和一组 interface 来创建动态代理类; 通过反射机制获得动态代理类的构造函数,其唯一参数类型是调用处理器接口类型; 通过构造函数创建动态代理类实例,构造时调用处理器对象作为参数被传入。

8. Spring-AOP 8.1 概念

面向切面编程

切面(aspect):日志,事物等需要插入的程序

切入点(pointcut):要插入的service类的位置(某个方法前或后)

通知(advice):切面中的方法

目标(target):被切入的对象

代理(proxy):被切入对象的代理类 (切入切面而创建的代理类,实际切入对象)

8.2 方式一:使用Spring原生API实现AOP
  1. 切面实现MethodBeforeAdvice AfterReturningAdvice等方法

    public class BeforeLog implements MethodBeforeAdvice {
        public void before(Method method, Object[] args, Object target) throws Throwable {
            System.out.println("这里执行的是"+method.getName()+",他的参数是"+args+",被切入的对象是"+target.getClass().getName());
    
        }
    }

2.xml中配置切入点 切入动作等

   
    
    

    
    
    

3.测试

public class Test {
    @org.junit.Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
        Demo demo = context.getBean("demoImpl", Demo.class);
        demo.insert();
    }
}

实际上就是Spring使用动态代理创建代理类,在调用处理器中的invoke里通过反射调用代理类的方法时,在其前后插入事物

8.3 方法二:使用自定义切面实现AOP

1.创建自定义切面

public class Log {
    
    public void before(){
        System.out.println("这是自定义的方法前切面");
    }
   
    public void after(){
        System.out.println("这是自定义的方法后切面");
    }
}

2.在xml中注册切面


    
    
        
            
            
            
        
    

3.测试

8.4 方法三:使用纯注解实现AOP

1.创建自定义切面,并使用注解注入Spring容器

@Component
@Aspect
public class Log {
    @Before("execution(* com.xiaofeng.serviceImpl.DemoImpl.*(..))")
    public void before(){
        System.out.println("这是自定义的方法前切面");
    }
    @After("target(com.xiaofeng.serviceImpl.DemoImpl)")
    public void after(){
        System.out.println("这是自定义的方法后切面");
    }
}

这里涉及component用法:使用xml开启事物的compoent方式 代理类也通过这种方式注入

  1. xml中开启事务支持

    
    
        
        
        
        
        

9. Spring-mybatis 核心思想:

把mybatis的配置文件,sqlSessionFactory,sqlSession对象化 全部注入包装到Spring中 由Spring代理创建实例 将mybatis代码完全封装在Spring容器中,增加复用性,方便管理

步骤:

9.1 导包
 
            org.springframework
            spring-webmvc
            5.3.10
        
        
            mysql
            mysql-connector-java
            8.0.26
        
        
            junit
            junit
            4.11
        

        
            org.aspectj
            aspectjweaver
            1.9.4

        
        
            org.mybatis
            mybatis
            3.5.7
        
        
            org.mybatis
            mybatis-spring
            2.0.6
        

        
            org.springframework
            spring-jdbc
            5.3.10
        

    
        
            
                src/main/java
                
                    ***.xml
                
                false
            
            
                src/main/resources
                
                    ***.xml
                
                false
            
        
    

9.2 配置mybatis在Spring的基础配置 9.2.1 注入datasource Bean org.springframework.jdbc.datasource.DriverManagerDataSource
   

        
        
        
        
    
9.2.2 注入SqlSessionFactory org.mybatis.spring.SqlSessionFactoryBean
    
        
        
        
        
        
    
9.2.3 注入sqlSession org.mybatis.spring.SqlSessionTemplate
    
        
    
9.3 构造Dao动作等

1.创建数据库映射对象

User

2.创建Mapper接口

public interface UserMapper {
    public List query();
}

3.在mybatis配置中写sql






    select * from mybatis.user;



4.创建mapper实例(把sqlSessionTemplate作为属性传入,通过sqlSessionTemplate获取mapper,实际就是包装了mybatis的getMapper过程)

public class UserMapperImpl implements UserMapper{
    private SqlSessionTemplate sqlSessionTemplate;
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }
    public List query() {
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        return mapper.query();
    }
}

5.注入mapper到Spring


        
    

6.测试

public class Test {
    @org.junit.Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
        UserMapper userMapper = context.getBean("UserMapper", UserMapper.class);
        List list = userMapper.query();
        for (User user:list) {
            System.out.println(user);
        }
    }
}
10. 事务(Spring事务管理)

事务的几大原则: 自行百度

    
        
    
    
    
    
        
            
            
        
    
    
        
        
    

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

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

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