spring学习

Spring

一.简介

1.简介

理念:使现有的技术更加容易使用。

SSH :Sttruct2+spring+Hibernate

SSM: SpringMVC+Spring +Mybatis

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

 <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

2.优点

  • 开源免费
  • 轻量级,非入侵式
  • 控制反转(IOC) ,面向切面编程(AOP)
  • 框架整合

spring是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架

3.组成

4.拓展

现代化的JAVA开发:基于spring的开发

  • SpringBoot
    • 一个快速开发的脚手架
    • 可以快速的开发单个微服务
    • 约定大于配置
  • Spring Cloud
    • 基于SpringBoot实现。

现在大多数公司都在使用springBoot。 学习springBoot的前提是完全掌握spring和springMVC!

二.IOC理论推导

1.理论推导

  1. UserDAO接口
  2. UserDAOImpl实现类
  3. UserService 业务接口
  4. UserServiceImpl业务实现类

在我们之前的业务中,用户的需求可能会影响我们原来的代码,因为我们需要根据用户的需求去修改我们原来的代码。

我们使用一个set接口实现:

 private UserDAO userDAO;
  //利用set进行动态实现值的注入。
 public void setUserDAO(UserDAO userDAO){
     this.userDAO=userDAO;
 }
  • 之前,程序是主动创建对象,控制权在程序员手上。
  • 使用了set注入,程序不再具有主动性,而是变成了被动的

这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了,系统的耦合性大大降低,可以更加专注的在业务的实现上,这是IOC的原型。

2.本质

控制反转是一种通过描述(XML/注解)并通过第三方去生产或获取特定对象的方式。在spring中实现控制反转的是IOC容器,1其实现的方法是依赖注入。

三.HelloSpring

四.IOC创建对象的方式

  1. 使用无参构造创建对象,默认!

  2. 假设我们要使用有参构造创建对象。

    1. 下标赋值

      <bean id="user" class="com.wang.pojo.User">
          <constructor-arg index="0" value="小柒"/>
      </bean>
      
    2. 类型

       <bean id="user" class="com.wang.pojo.User">
          <constructor-arg type="java.lang.String" value="xiaoqi"/>
       </bean>
      
    3. 直接通过参数名

      <bean id="user" class="com.wang.pojo.User">
              <constructor-arg name="name" value="小柒"/>
          </bean>
      

五.Spring配置

1.别名

<!--别名,如果添加了别名,我们也可以使用别名获取到这个对象-->
<alias name="user" alias="userNew"/>

2.Bean的配置

<!--
   id: bean的唯一标识符,也就是相当于我们学的对象名
   class: bean 对象所对应的全限定名: 包名+类型
   name: 也是别名,而且name可以同时取多个别名
-->
    <bean id="userT" class="com.wang.pojo.UserT" name="user2,u2">
        <property name="name" value="小柒"/>

    </bean>

3.import

这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个。

假设现在项目中有多个人开发,这三个负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的

  • 张三

  • 李四

  • 王五

  • applicationContext.xml

    <import resource="beans.xml"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>
    

使用的时候,直接使用总的配置就可以了

六.DI依赖注入

1.构造器注入

2.set方式注入

  • 依赖注入:Set注入
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,由容器来注入。

环境搭建:

1.复杂类型

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

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

2.真实测试对象

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> games;
    private String wife;
    private Properties info;
}

3.beans.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
         https://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="student" class="com.wang.pojo.Student">
<!--第一种,普通值注入,value-->
        <property name="name" value="小柒"/>
    </bean>
</beans>

4.测试类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());
    }
}

5.完全注入信息


    <bean id="address" class="com.wang.pojo.Address">
        <property name="address" value="江苏"/>
    </bean>
    <bean id="student" class="com.wang.pojo.Student">
<!--第一种,普通值注入,value-->
        <property name="name" value="小柒"/>
<!--第二种,Bean注入,ref-->
        <property name="address" ref="address"/>
<!--数组注入,ref-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>
<!--list注入-->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看电视</value>
            </list>
        </property>
<!--map-->
        <property name="card">
            <map>
                <entry key="身份证" value="12345712345612345678"/>
                <entry key="银行卡" value="12345324643646346436"/>
            </map>
        </property>
<!--set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>
<!--null-->
        <property name="wife">
            <null/>
        </property>
<!--Properties-->
        <property name="info">
            <props>
                <prop key="学号">1203031033</prop>
                <prop key="性别"></prop>
                <prop key="姓名">小刘</prop>
            </props>
        </property>
    </bean>

3.拓展方式注入

我们可以使用p命名空间和c命名空间进行注入

官方解释:

<?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:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">

<!--p命名空间注入,可以直接注入属性值:property-->
    <bean id="user" class="com.wang.pojo.User" p:name="小柒" p:age="18"/>

    <!--c命名空间注入,通过构造器注入:construct-args-->
    <bean  id="user2" class="com.wang.pojo.User" c:age="18" c:name="小柒"/>
</beans>

测试:

@Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
        User user =context.getBean("user2",User.class);
        System.out.println(user);

    }

注意点:p命名空间和c命名空间不能直接使用,必须导入xml约束

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

4.Bean的作用域

  1. 代理模式(Spring默认机制)

    <bean  id="user2" class="com.wang.pojo.User" c:age="18" c:name="小柒" scope="singleton" />
    <!--true-->
    
  2. 原型模式: 每次从容器中get的时候,都会产生一个新对象!

    <bean  id="user2" class="com.wang.pojo.User" c:age="18" c:name="小柒" scope="prototype" />
    <!--false-->
    
  3. 其余的request、session、application、这些个只能在web开发中使用到!

七.Bean的自动装配

  • 自动装配是spring满足bean依赖一种方式
  • Spring会在上下文中自动寻找,并自动给bean装配属性!

在Spring中有三种装配的方式

  1. 在xml中显示的配置
  2. 在java中显示配置
  3. 隐式的自动装配bean【重要】

1.测试

环境搭建:一个人有两个宠物!

2.ByName自动装配

<bean id="cat" class="com.wang.pojo.Cat"/>
<bean id="dog" class="com.wang.pojo.Dog"/>

<!--
byName: 会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!
-->
<bean id="people" class="com.wang.pojo.People" autowire="byName">
    <property name="name" value="小柒呀"/>
</bean>

3.ByType自动装配

    <bean class="com.wang.pojo.Cat"/>
    <bean class="com.wang.pojo.Dog"/>

    <!--
    byName: 会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!
    byType: 会自动在容器上下文中查找,和自己对象属性类型相同的bean!
    -->
    <bean id="people" class="com.wang.pojo.People" autowire="byType">
        <property name="name" value="小柒呀"/>
    </bean>

小结:

  • byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
  • bytype的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!

4.使用注解实现自动装配

使用注解须知:

  1. 导入约束:context约束

  2. ==配置注解的支持:context:annotation-config

    <?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
             https://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/aop
             https://www.springframework.org/schema/aop/spring-beans.xsd">
        <context:annotation-config/>
    </beans>
    

@Autowired

直接在属性上使用即可,也可以在set方式上使用!

使用Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byname!

科普:

@Nullable    字段标记了这个注解,说明这个字段可以为null;
public @interface Autowired {
    boolean required() default true;
}

测试代码

public class People {
    //如果显示定义了Autowired的require属性为false,说明这个对象可以为null。否则不允许为空
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解完成的时候,我们可以使用@Qualifier(value = “xxx”)去配置@AUtowired的使用,指定一个唯一的bean对象注入!

public class People {
    @Autowired
    @Qualifier(value = "cat")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog")
    private Dog dog;
    private String name;
}

@Resource注解

public class People{
    @Resource(name="cat2")
    private Cat cat;
 
    @Resource
    private Dog dog;
}

小结:

@Resource和@Autowired的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autowired通过byType的方式实现,必须要求这个对象存在【常用】
  • @Resource默认通过byname的方式实现,如果找不到名字,则通过ByType实现!如果两个都找不到的情况下,就报错。【常用】
  • 执行顺序不同:@Autowired通过byType的方式实现,@Resource默认通过byname的方式实现

八.使用注解开发

在spring4注解之后,要使用注解开发,必须要保证aop的包导入了

使用注解需要导入context约束,增加注解的支持!

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
</beans>

1.bean

2.属性如何注入

@Component
public class User {
    @Value("xiaoqi")
    public void setName(String name) {
        this.name = name;
    }

    //相当于<property name="name" value="xiaoqi"/>

    public String name;
}

3.衍生的注解

@Component有几个衍生注解,我们在web开发中。会按照mvc三层架构分层!

  • dao 【@Repository】

  • service 【@Service】

  • controller 【@Controller】

    这四个注解功能都是一样的,都是代表将某个类注册到spring中,装配Bean

4.自动装配

  1. @Autowired: 自动装配通过类型,名字 。如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value=“xxx”)
  2. @Nullable 字段标记了这个注解,说明这个字段可以为null
  3. @Resource: 自动装配通过名字,类型

5.作用域

@Component
@Scope("prototype")
public class User {
    @Value("xiaoqi")
    public void setName(String name) {
        this.name = name;
    }

    //相当于<property name="name" value="xiaoqi"/>

    public String name;
}

6.小结

xml与注解

  • xml更加万能,适用于任何场合,维护简单方便
  • 注解不是自己的类,使用不了,维护相对复杂!

xml与注解的最佳实践:

  • xml用来管理bean;

  • 注解只负责完成属性的注入;

  • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持。

    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.wang"/>
    <context:annotation-config/>
    
  • 22
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值