Spring基础1

Spring

简介

Spring:春天---->给软件行业带来了春天

2002,首次推出了Spring框架的雏形:interface21框架

Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日,发布了1.0正式版

Spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架

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



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

官方文档:https://docs.spring.io/spring-framework/docs/5.2.9.RELEASE/spring-framework-reference/

优点

Spring是一个开源的免费的框架(容器)

Spring是一个轻量级的,非入侵式的框架

控制反转(IOC),面向切面编程(AOP)

支持事务的处理,对框架整合的支持

总结:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架

IOC理论推导

UserDao接口

UserDaoImpl实现类

UserService业务接口

UserServiceImpl业务实现类

在之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改源代码,如果程序代码量十分大,修改一次的成本代价十分昂贵

package com.company.dao;

public interface UserDao {
    void getUser();
}
package com.company.dao;

public class UserDaoImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("默认获取用户的数据");
    }
}

package com.company.dao;

public class UserDaoMysqlImpl implements UserDao{
    @Override
    public void getUser() {
        System.out.println("默认获取Mysql的数据");
    }
}
package com.company.service;

public interface UserService {
    void getUser();
}
package com.company.service;

import com.company.dao.UserDao;

public class UserServiceImpl implements UserService{

    private UserDao userDao;

    public void setUserDao(UserDao userDao){
        this.userDao = userDao;
    }
    @Override
    public void getUser() {
        userDao.getUser();
    }
}
import com.company.dao.UserDaoMysqlImpl;
import com.company.service.UserService;
import com.company.service.UserServiceImpl;
import org.junit.Test;

public class MyTest {


    @Test
    public void test1(){
        UserService userService = new UserServiceImpl();
        ((UserServiceImpl) userService).setUserDao(new UserDaoMysqlImpl());
        userService.getUser();
    }
}

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

package com.company.service;

import com.company.dao.UserDao;

public class UserServiceImpl implements UserService{

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

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

IoC本质

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的

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

HelloString

pojo

package com.company.pojo;

public class Hello {
    private String str;

    public void setStr(String name) {
        this.str = name;
    }

    public String getStr() {
        return str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

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">

<!--
value:具体的值,基本数据类型
ref:引用Spring容器中创建好的对象
-->

    <!--使用Spring来创建对象,在Spring这些都称为Bean-->
    <bean id="hello" class="com.company.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>



</beans>

测试

import com.company.pojo.Hello;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SuppressWarnings("all")
public class Mytest {





    @Test
    public void test(){

        //获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象现在都在Spring中的管理了,我们要使用,直接去里面取出来就可以
        Hello hello =(Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

IoC创建对象的方式

  • 使用无参构造创建对象,默认
  • 假设我们要使用有参构造创建对象
<!--第一种下标赋值-->
<bean id="user" class="com.company.pojo.User">
    <constructor-arg index="0" value="ming"/>
</bean>
<!--第二种类型创建,不建议使用-->
<bean id="user" class="com.company.pojo.User">
    <constructor-arg type="java.lang.String" value="gg"/>
</bean>
<!--第三种直接通过参数名赋值-->
<bean id="user" class="com.company.pojo.User">
    <constructor-arg name="name" value="方法"/>
</bean>

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了,

Spring配置说明

别名

<alias name="user" alias="aaa"/>

如果添加了别名,两个名字都能取出来

bean的配置

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

import

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

<import resource="beans.xml"/>                    <!--创建xml的时候,主xml设置为beans而不是create applicationcontext-->

依赖注入

构造器注入

set方式注入

依赖注入:Set注入!

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

环境搭建:

  • 复杂类型:

  • package com.company.pojo;
    
    import java.util.List;
    import java.util.Map;
    import java.util.Properties;
    import java.util.Set;
    
    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;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Address getAddress() {
            return address;
        }
    
        public void setAddress(Address address) {
            this.address = address;
        }
    
        public String[] getBooks() {
            return books;
        }
    
        public void setBooks(String[] books) {
            this.books = books;
        }
    
        public List<String> getHobbys() {
            return hobbys;
        }
    
        public void setHobbys(List<String> hobbys) {
            this.hobbys = hobbys;
        }
    
        public Map<String, String> getCard() {
            return card;
        }
    
        public void setCard(Map<String, String> card) {
            this.card = card;
        }
    
        public Set<String> getGames() {
            return games;
        }
    
        public void setGames(Set<String> games) {
            this.games = games;
        }
    
        public String getWife() {
            return wife;
        }
    
        public void setWife(String wife) {
            this.wife = wife;
        }
    
        public Properties getInfo() {
            return info;
        }
    
        public void setInfo(Properties info) {
            this.info = info;
        }
    }
    
    package com.company.pojo;
    
    public class Address {
        private String address;
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    }
    
  • 真实测试对象

拓展方式注入

<?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">


    <bean id="address" class="com.company.pojo.Address"/>

    <bean id="student" class="com.company.pojo.Student">
        <!--普通值注入-->
        <property name="name" value="ming"/>
        <!--bean注入 ref-->
        <property name="address" ref="address"/>

        <!--数组注入-->
        <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="333"/>
                <entry key="银行卡" value="555"/>
                <entry key="学生卡" value="xxx"/>
            </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="学号">1771733</prop>
                <prop key="性别">男</prop>
                <prop key="姓名">明明</prop>
            </props>
        </property>
    </bean>

</beans>

c命名和p命名空间注入

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
<!--p命名空间注入,可以直接注入属性的值:property-->
<bean id="user" class="com.company.pojo.User" p:name="明明" p:age="18"/>
ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
User user = context.getBean("user", User.class);

System.out.println(user.toString());
<!--c命名空间注入,通过构造器注入:constructor-arg-->
<bean id="user2" class="com.company.pojo.User" c:age="18" c:name="mingming"/>

bean的作用域

<bean id="user2" class="com.company.pojo.User" c:age="18" c:name="mingming" scope="singleton"/>

单例模式:默认是单例,但也可以显示加上

原型模式:每次从容器中get的时候,都会产生一个新对象

其余的request,session,application这些个只能在web开发中使用到

自动装配bean

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

在Spring中有三种装配的方式

  • 在xml中显示的配置
  • 在java中显示的配置
  • 隐式的自动装配bean

测试

环境搭建

<?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">


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

    <bean id="people" class="com.company.pojo.People">
        <property name="name" value="ming"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>
</beans>
  • 一个人有两个宠物

自动装配

<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
-->
<bean id="people" class="com.company.pojo.People" autowire="byName">
    <property name="name" value="ming"/>
</bean>
<!--byType:会自动在容器上下文中查找,和自己对象set属性类型相同的bean-->
<bean id="people" class="com.company.pojo.People" autowire="byType">
    <property name="name" value="ming"/>
</bean>
  • byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
  • byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致

使用注解实现自动装配

要使用注解须知:

<?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>

@Autowired

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

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

@Autowired(required=false)
//如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空


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

@Resource 既可以名字查找,也可以类型查找,要保证任一唯一

也可以指定名字

@Resource(name=“xxx”)

@Resource和@Autowired区别

  • 都是用来自动装配的,都可以放在属性字段上

  • @Autowired通过byType的方式实现,而且必须要求这个对象存在(常用),找不到则通过byName,如果不能自动装配,需要配合@Qualifier(value=“xxx”)

  • @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现,如果两个都找不到的情况下就报错

  • 执行顺序不同,@Autowired默认通过byType,@Resource默认通过byName,找不到再换第二种方式

@Nullable :字段标记了这个注解,说明这个字段可以为null

Spring注解开发

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

    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.company.pojo"/>
    <context:annotation-config/>
  



</beans>
  • bean

  • 属性如何注入

  • @Scope(“prototype”)

  • singleton

  • 选择bean是单例或是原型

    package com.company.pojo;
    
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    
    //@Component 组件
    @Component
    public class User {
    
        @Value("ming")
        public String name;
    
    }
    
  • 衍生的注解

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

    • dao @Repository

    • service @Service

    • controller @Controller

      这四个注解功能是一样的,都是代表将某个类注册到Spring容器中,装配bean

  • 自动装配注解

  • 作用域

  • 小结

    • xml与注解

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

      • xml用来管理bean
      • 注解只负责完成属性的注入
      • 使用过程中,只需要注意,必须让注解生效,就要开启注解支持

使用JavaConfig实现配置

我们现在要完全不使用Spring的xml配置了,全权交给java来做

JavaConfig是Spring的一个子项目,在Spring4之后,他成为了一个核心功能

package com.company.config;


import com.company.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration//这个也会被Spring容器托管,注册到容器中,因为他本来就是一个Component,
// @Configuration 代表这是一个配置类,
@ComponentScan("com.company.pojo")
@Import("config2.class")//引入其他配置类
public class MingConfig {


    //注册一个bean,id是这个方法的名字,class是这个方法的返回值
    @Bean
    public User getUser(){
        return new User();
    }
}

import com.company.config.MingConfig;
import com.company.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {




    @Test
    public void test(){

        //如果完全使用了配置类方式去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载
        ApplicationContext context = new AnnotationConfigApplicationContext(MingConfig.class);
        User user = (User) context.getBean("getUser");
        System.out.println(user.getName());
    }
}

posted @ 2020-10-16 19:34  yourText  阅读(100)  评论(0编辑  收藏  举报