java之spring(实训笔记)

1.概念

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

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

1.1.spring是什么

spring是一个开源框架,它由Rod Johnson创建的,它是为了解决企业应用开发的复杂性而创建的。

1.2.优点

spring是一个开源,免费的框架(容器)。 容器 来存放 bean

spring是一个轻量级,非入侵式的框架。导入jar包就可使用。

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

支持事务的处理(声明式事务),对框架的整合(几乎能整合所有的框架)。

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

控制:程序员对创建对象的权利,

反转:将程序员创建对象的权利 交给容器,

bean --> spring 容器 : bean的创建,bean的消亡 -->bean的整个生命流程 都由spring容器管理

2. IOC

2.1.IOC理论推导

之前创建项目:

1.UserDao 接口 写方法

2.UserDaoImpl 接口实现类 继承UserDao 重写UserDao里的方法

3.UserService 业务接口 写的也是方法

4.UserServiceImpl 业务实现类 继承UserService,重写UserService方法,但实际上调用的是userDao的方法。

//如果你想要新增业务,比如 查看图书,就必须在UserServiceImpl 修改代码
//private UserDao userDao =new UserDaoBookImpl();
//我们增加了类,改变原来的代码
//因为客户的需求,我们要去修改原来的代码,

//利用IOC的思想
//将UserServiceImpl 里
//private UserDao userDao =new UserDaoBookImpl();改变为
//private UserDao userDao; 并给上set方法,
//我们在启动类里,先把需要实现的业务new出来,然后set给值,在通过getUser()方法 输出。
//在之前的业务中,用户的需求的可能会影响我们原来的代码,我们需要根据用户的需求去修改原来的代码!
//如果程序代码量十分大,修改一次的成本代价十分昂贵!
//这种思想,从本质上解决的问题,我们程序员不需要再去主动的创建对象,系统的耦合性大大降低。
//再来思考,控制反转,反转的是创建对象的权利,由程序员交给了程序(容器)。

 private UserDao userDao;
// 利用set方法来实现动态值的注入
 public void setUserDao(UserDao userDao) {
  this.userDao = userDao;
 }

2.2.IOC本质

控制反转IOC(Inversion of Control)是一种设计思想,DI(依赖注入)是实现IOC的一种方式,也有人认为DI是IOC的另一种说法,没有IOC的程序中,我们使用面向对象编程,对象的创建和对象的对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,我个人认为的控制反转就是:获得依赖对象的方式反转了。

图1,每个组件或者项目,都是互相关联的,一层调一层,耦合度高。

图2,有了IOC容器作为第三方,容器来连接这些个体,通过容器来管理这些个体,用户想要调用这些个体,直接调用第三方容器,实现了解耦。

// 如果你想要换业务,就必须在这里修改代码
// private UserDao userDao =new StudentDaoImpl(); //new之后 和上一层有直接关系 相当于绑定了

 private UserDao userDao; // 我们在层与层之间设置了 接口,通过接口的方式来调用 解耦
// 利用set方法来实现动态值的注入
 public void setUserDao(UserDao userDao) {
  this.userDao = userDao;
 }

new之后 和上一层有直接关系 相当于绑定了,我们通过接口的方式 private UserDao userDao;来调用,实现解耦。

IOC是Spring容器的核心内容,使用多种方式完美的实现了IOC,可以使用XML配置,也可以使用注解。

spring容器在初始化时先读取配置文件,根据配置文件或者元数据创建与组织对象(bean)存入容器中,程序使用时再从IOC容器中取出需要的对象。

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

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

3.XML装配bean

public class Student {
 private String name;
 public void setName(String name) {
  this.name = name;
 }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!--使用spring来创建对象,在spring中这些都成为bean-->
    <bean id="student" class="com.gm.pojo.Student">
        <property name="name" value="张三"/>
    </bean>
</beans>
关于xml注册bean

1.使用spring来创建对象,在spring中这些称为bean
使用bean标签,id 是起的名字,class是类所在的路径,property给类的属性赋值
value 是赋值, ref是指向已经注册过的bean

2.xml注册的bean调用
 首先要获取spring的上下文对象,参数里是你的xml文件
 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
 第二步通过getBean方法去拿对象,参数里是对象在xml里的id
 context.getBean("")

思考
1.xml是怎么装配bean的?
set方法,加上toSpring方式后,输出的hash码会变成UTF-8。现实中文
2.Student是由谁创建的?
spring容器创建的
3.Student的属性是由谁设置的?
spring容器设置的
这个过程就叫做控制反转。
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用spring之后,对象是由容器创建的。
反转:程序本身不创建对象,而是变成被动的接收对象。
依赖注入:就是利用set方法来进行注入的。
IOC是一种思想,由主动的编程变成被动的接收。

到了现在,我们彻底不用再去程序中改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC,
就是:对象由spring来创建,管理,装配。

4.IOC创建对象的方式

4.1.默认的无参构造方法,创建对象

public class User {
 private String name;
 public User(){
//  无参构造是默认的
  System.out.println("我是无参构造!");
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public void show(){
  System.out.println("name="+name);
 }
}
1.默认的无参构造方式,创建对象
无参构造是默认的,即使你不写它也会存在,
public User(){
    System.out.println("我是无参构造!");
}
我们在无参构造方法里sout,是为了输出信息,来确认无参构造是否默认运行的

4.2.有参构造创建对象

4.2.1.通过下标

 <!--通过下标赋值-->
    <bean id="student" class="com.gm.pojo.Student">
        <constructor-arg index="0" value="李四"/>
    </bean>

4.2.2.通过类型(不建议使用)

如果我有多个参数都是string?

 <!--通过类型 不是基本类型必须写全限定名-->
    <bean id="student" class="com.gm.pojo.Student">
        <constructor-arg type="java.lang.String" value="王五"/>
    </bean>

4.2.3.通过参数名

  <!--通过参数名 把它当作一个bean-->
    <bean id="student" class="com.gm.pojo.Student">
        <constructor-arg name="name" value="赵六"/>
    </bean>

注意:spring容器会把所 有的bean统一管理,当你的bean被注册到容器里后,就被spring实例化。类似于一个婚介所 所以会有以下的输出结果。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vt3Lf3F5-1638193840628)(C:\Users\gm_admin\Desktop\实训课件\day1:spring\图片\image-20211124150956546.png)]

5.spring配置

5.1.别名

 <!--别名,给bean起个别名 相当于他有两个名字-->
 <alias name="student" alias="student2"/>
<!--通过参数名 把它当作一个bean 通过name也可以起别名,还可以起多个别名,相对于alias还要更高级-->
<bean id="student" class="com.gm.pojo.Student" name="student3">
    <constructor-arg name="name" value="赵六"/>
</bean>

5.2.import

    <!--导入其他的xml文件,用于团队开发,import只能导入其他的Spring配置文件-->
    <import resource="bean.xml"/>

6.依赖注入(DI)

依赖注入 Dependency Injection

6.1.构造器注入

前面已经讲过了,默认的无参构造,有参构造 通过下标,类型(不推荐),参数名

6.2.set方式注入(重点)

依赖:bean对象的创建依赖于容器

注入:bean对象的所有属性通过容器来注入

	<bean id="address" class="com.gm.pojo.Address">
        <property name="address" value="河南郑州"/>
    </bean>
    <bean id="student" class="com.gm.pojo.Student">
        <!--普通值注入-->
        <property name="name" value="张三"/>
        <!--引用类型注入,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>rap</value>
                <value>篮球</value>
            </list>
        </property>
        <!--set注入-->
        <property name="games">
            <set>
                <value>lol</value>
                <value>王者荣耀</value>
                <value>吃鸡</value>
                <value>斗地主</value>
            </set>
        </property>
        <!--map注入-->
        <property name="card">
            <map>
                <entry key="身份证" value="123123123123"/>
                <entry key="银行卡" value="678923123123"/>
            </map>
        </property>
        <!--null注入-->
        <property name="wife">
            <null/>
        </property>
        <!--配置类注入-->
        <property name="info">
            <props>
                <prop key="url">20211125</prop>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>

6.3.拓展方式注入

p命名空间注入 对应的是 属性注入

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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="user" class="com.gm.pojo.User" p:name="张三" />

    </beans>

c命名空间注入 对应的是 构造器注入

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:c="http://www.springframework.org/schema/c"
       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="user2" class="com.gm.pojo.User" c:name="李四"/>
    </beans>

7.bean的作用域

scope

8.bean的自动装配

spring有三种装配方式

1.在xml显式的装配

    <bean id="cat" class="com.gm.pojo.Cat"/>
    <bean id="dog" class="com.gm.pojo.Dog"/>
    <bean id="people" class="com.gm.pojo.People">
        <property name="name" value="张三"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>

2.在Java中显式的装配 以后会讲

3.隐式的自动装配(重要)

8.1.byName方式

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

        <!--会自动在容器上下文查找,和自己对象set方法后面的值对应的bean的id-->
        <bean id="people" class="com.gm.pojo.People" autowire="byName"/>

比如:Cat

 public void setCat(Cat cat) {
  this.cat = cat;
 }

8.2.byType方式

        <!--会自动在容器上下文查找,和自己对象属性类型相同的bean,必须保证这个类型上下文唯一-->
        <bean id="people" class="com.gm.pojo.People" autowire="byType"/>

8.3.基于注解实现自动装配

jdk 1.5 支持注解

spring2.5支持注解

@Autowired直接作用在属性上

@Autowired
 private Cat cat;
 @Autowired
 private Dog dog;
 private String name;

拓展:

@Resource 也能实现装配

@Qualifier 配合 @Autowired 使用

感兴趣 自己去了解

要使用注解 须知:

1.导入约束 context

2.配置注解的支持

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       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
http://www.springframework.org/schema/context/spring-context.xsd">

  <!--注解支持-->
    <context:annotation-config/>

    <!--注解扫描 指定要扫描的包,这个包下的注解就会生效 对应的类中使用@Component 将类注册为组件-->
    <context:component-scan base-package="com.gm"/>

</beans>

属性如何注入?

@Component
public class User {
// public String name ="zhangsan";
 public String name;
 public String getName() {
  return name;
 }
 @Value("zhangsan")
 public void setName(String name) {
  this.name = name;
 }
}

直接赋值,或者使用@Value注解,@Value还可以作用在set方法上

关于@Component注解衍生注解,在开发中,我们分3层架构

Dao (mapper)-- @Repository

Service – @Service

Controller – @Controller

他们的作用是一样的,都是将类注册为组件,交给spring容器托管。

9.使用Java的方式配置spring完全代替xml

我们现在完全不使用spring的xml配置,完全交给Java。

配置类

/**
 * @author gm
 * 配置类
 * 加上@Configuration注解后,就相当于 该类是spring的xml配置文件
 */
@Configuration
public class GmConfig {

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

实体类

@Component
public class User {
 @Value("zhangsan")
 private String name;

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

启动类

public class Application {
 public static void main(String[] args) {
//  使用注解的方式需要使用AnnotationConfigApplicationContext,里边是配置类
  ApplicationContext context = new AnnotationConfigApplicationContext(GmConfig.class);
// 使用注解,getBean的name 为方法名
  User user = context.getBean("getUser", User.class);
  System.out.println(user.getName());
 }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值