Spring IOC 配置 注解自动装配

1.Spring的的历史

**总览 :历史,设计理念,反馈,入门。
核心 :IoC容器,事件,资源,i18n,验证,数据绑定,类型转换,SpEL,AOP。
测试中 :模拟对象,TestContext框架,Spring MVC测试,WebTestClient。
资料存取 :事务,DAO支持,JDBC,O / R映射,XML编组。
Web Servlet :Spring MVC,WebSocket,SockJS,STOMP消息传递。
网络反应 :Spring WebFlux,WebClient,WebSocket。
积分 :远程处理,JMS,JCA,JMX,电子邮件,任务,调度,缓存。
语言能力 :Kotlin,Groovy,动态语言。

框架:
SSH : Struct2 + Spring + Hibernate!
SSM : SpringMvc + Spring + Mybatis

2. 历史

1.1Spring:春天------> 给软件行业带来了春天!
Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于*2004年3月24日,*发布了1.0正式版。

#####Rod Johnson ,Spring Framework创始人,著名作者。很难想象Rod Johnson的学历,真的让好多人大吃一惊,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学

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

优点:
Spring是一个免费的开源框架(容器)
Spring是一个轻量级的,非入侵式的框架
是一个IOC(控制反转) AOP(面向切面编程)
支持事物的处理,对框架整合支持

3.第一个spring 程序hello Spring

3.1.1导入Spring相关jar包

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.2.RELEASE</version>
    </dependency>
    <!--测试类的包-->
        <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

3.1.2编写一个实体类 hello 添加一个空擦构造和set方法

public class Hello {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("hello"+name);
    }
}

3.1.3编写Spring配置文件命名为SpringBean.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">
<!--取别名alias 可以给我们的bean设置别名,可以多个用逗号隔开-->
    <alias name="hello" alias="hello2"/>
<!--id:bean唯一的表示,对象名
    name;就是bean别名
    class;bean的全类名-->
    <bean id="hello" name="hello3" class="com.heng.pojo.Hello">
        <property name="name" value="Spring"/>
    </bean>
</beans>

3.1.4 测试类


    @Test
    public void test2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("SpringBean.xml");
        Hello hello = (Hello) context.getBean("hello2");
        hello.show();
    }

在这里插入图片描述

3. IOC设计理念

IOC是一种编程思想 , 由主动的编程变成被动的接收 .这个过程就叫做控制反转

**控制:**谁来控制对象的创建,传统的应用程序的对象时由程序本身控制创建的,使用Spring后,对象是由Spring来创建的
**反转:**程序本身不创建对象,而变为被动的接收者
依赖注入:就是使用set方法来进行注册
创建好一个Spring就可以不用再去程序里面改动,要实现不同的操作,只需要在xml文件中进行修改,所谓的IOC,就是对象那个由Spring来建造,管理,装配

4. Spring配置

4.1别名

<!--取别名alias 可以给我们的bean设置别名, 也可以取别名在bean里面 name="hello2","hello3" 别名可以多个用逗号隔开就好-->
    <alias name="hello" alias="hello2"/>
     <bean id="hello" name="hello3" class="com.heng.pojo.Hello">
        <property name="name" value="Spring"/>
    </bean>

4.2 Bean配置

<!--id:bean唯一的表示,对象名
    name;就是bean别名
    class;bean的全类名
    properyt 参数类型
    value 要传入的参数
    -->
    <bean id="hello" name="hello3" class="com.heng.pojo.Hello">
        <property name="name" value="Spring"/>
    </bean>

4.3 import 属性注入 可以配置多个xxx.xml文件合并为一个总的,适用于团队开发

 <import resource="hello.xml"/>
 <import resource="hello2.xml"/>
 <import resource="hello3.xml"/>

5.依赖注入

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

5.1 Set 方式注入{重点}

环境搭建

5.1.1 复杂类型
public class Address {
    private String address;

    public Address(String address) {
        this.address = address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}
5.1.2 真实测试对象
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> list;
    private Map<String,String> map;
    private Set<String> set;
    private String wife;//null
    private Properties info;

    public void setName(String name) {
        this.name = name;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public void setBooks(String[] books) {
        this.books = books;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
    public void setMap(Map<String, String> map) {
        this.map = map;
    }
   public void setSet(Set<String> set) {
        this.set = set;
    }
    public void setWife(String wife) {
        this.wife = wife;
    }
    public void setInfo(Properties info) {
        this.info = info;
    }
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", list=" + list +
                ", map=" + map +
                ", set=" + set +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}
5.1.3 beans.xml 注册信息
  <bean id="address" class="com.heng.pojo.Address">
        <property name="address" value="长江"/>
    </bean>
    <bean id="student" class="com.heng.pojo.Student">
        <!--第一种,普通注入,value-->
        <property name="name" value="疯狗典"/>
        
  <!--autowire="byName" 自动匹配寻找和属性相关的bean 本质是set方法,会自动匹配bean
    autowire="byType" 根据这个属性去匹配-->
        <!--第二种,Bean 注入,ref-->
        <property name="address" ref="address"/>

        <!--array数组-->
        <property name="books">
            <array>
                <value>梁山伯</value>
                <value>祝英台</value>
                <value>花蝴蝶</value>
            </array>
        </property>

        <!--List 集合-->
        <property name="list">
            <list>
                <value>看电影</value>
                <value>逛街</value>
                <value>吃饭</value>
                <value>一条龙</value>
            </list>
        </property>

        <!--Map 集合 entry一行-->
        <property name="map">
            <map>
                <entry key="身份证" value="522127199903021215"/>
                <entry key="银行卡" value="522127199903021215"/>
            </map>
        </property>

        <!--Set-->
        <property name="set">
            <set>
                <value>lol</value>
                <value>qqf</value>
                <value>游戏</value>
            </set>
        </property>

        <!--null-->
        <property name="wife">
            <null/>
        </property>

        <!--properties 属性-->
        <property name="info">
            <props>
                <prop key="drver">20200223</prop>
                <prop key="url"></prop>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>
</beans>
5.1.4 测试
    @Test
    public  void test4(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
    }

在这里插入图片描述

5.2 拓展方式注入

我们可以使用 p命令空间和c命令空间进行注入 注意点:p命名和c命名空间不能直接使用,需要导入xml约束!
xmlns:c=“http://www.springframework.org/schema/c”
xmlns:p=“http://www.springframework.org/schema/p”
在这里插入图片描述

5.2.1 实体类
public class User {
    private String name;
    private  int age;

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

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

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void show() {
        System.out.println("name" + name+","+"age"+age);
    }
}
5.2.1 user.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"
       xmlns:context="http://www.springframework.org/schema/context"
       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/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

    <!--autowire="byName" 自动匹配寻找和属性相关的bean 本质是set方法,会自动匹配bean
    autowire="byType" 根据这个属性去匹配-->

    <!--p命名空间注入,可以直接注入属性-->
    <bean id="user" class="com.heng.pojo.User" p:name="张杰" p:age="25"/>
    <!--c命名空间注入,通过构造器-->
    <bean id="user2" class="com.heng.pojo.User" p:name="谢娜" p:age="35"/>


</beans>

在这里插入图片描述

5.2.2 测试
@Test
public void tsst5(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-User.xml");
    User user2 = context.getBean("user2", User.class);
    System.out.println(user2);
}

测试结果
在这里插入图片描述

5.3 bean的作用域

1.单例模式(Spring 默认机制)

    <!--p命名空间注入,可以直接注入属性-->
    <!--scope范围 singleton 独一个-->
    <bean id="user" class="com.heng.pojo.User" p:name="张杰" p:age="25" scope="singleton"/>

在这里插入图片描述
2.原型模式:每次从容器中get的时候,都会产生一个新对象!

   <!--c命名空间注入,通过构造器-->
    <!--原型模式:每一次从容器中get的时候都会产生一个新对象-->
    <bean id="user2" class="com.heng.pojo.User" p:name="谢娜" p:age="35" scope="prototype"/>

在这里插入图片描述
3.其余的 request、session、application、这些个只能在web开发中使用到

6. Bean的自动装配

Spring的三种装配方式
1.在xml中显示配置
2.在java中显示配置
3.隐式的自动装配bean【重点】****

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

6.1测试

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

public class Cat {
    public void show(){
        System.out.println("瞄");
    }
}
``狗类
```java
public class Dog {
    public  void show(){
        System.out.println("旺旺---");
    }
}

地址

public class Address {
    private String name;
    private Dog dog;
    private Cat cat;

    public void setName(String name) {
        this.name = name;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public void setCat(Cat cat) {
        this.cat = cat;
    }
    public String getName() {
        return name;
    }
    public Dog getDog() {
        return dog;
    }
    public Cat getCat() {
        return cat;
    }
    @Override
    public String toString() {
        return "Address{" +
                "name='" + name + '\'' +
                ", dog=" + dog +
                ", cat=" + cat +
                '}';
    }
}
6.1.1ByName自动装配

  <bean id="dog" class="com.heng.Tset2.Dog"/>
    <bean id="cat" class="com.heng.Tset2.Cat"/>
    <!--autowire="byName" 自动寻找和属性相关的bean,本质是set、方法,会自动匹配个个bean-->
    <bean id="add" class="com.heng.Tset2.Address" autowire="byName">
        <property name="name" value="主人"/>
        <!--<property name="cat" ref="cat"/>-->
        <!--<property name="dog" ref="dog"/>-->
    </bean>
6.1.2ByType自动装配
  <!--
    byName: 会自动在容器上下文中查找,和自己对象set方法后面的值对应的 beanid!
    byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
    -->
    <bean class="com.heng.Tset2.Cat"/>
    <bean class="com.heng.Tset2.Dog"/>
    <bean id="add2" class="com.heng.Tset2.Address" autowire="byType">
        <property name="name" value="主人"/>
    </bean>

手动装配:一个一个装配
自动装配:自动化赋值,不需要一个个赋值

6.2 使用注解自动装配

真实开发中使用注解进行开发
xxx.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"
    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>

6.2@Autowired和@Resource注解**区别都可以用来注入

  • 都是用来自动装配的,都可以放在属性字段上
  • @ Autowired 通过byType的方式实现,而且必须要求这个对象存在! 【常用】
  • @ Resource 默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错! 【常用】
  • 执行顺序不同:@ Autowired 通过byType的方式实现。@ Resource 默认通过byname的方式实现。**
public class Address {
    private String name;
    //@Autowired 是Spring的配置
    @Autowired(required = false) //自动注入装配  required = false 表示对象可以为空 ,默认为true
    @Qualifier("catt")//组合注解,通过它指定加载一个对象
    private Cat cat;

    //@Resource 是java的注解 也可以注入 可以通过属性指定一个对象
    @Resource(name = "dog2")
    private Dog dog;
    public Address() {
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public Dog getDog() {
        return dog;
    }
    public Cat getCat() {
        return cat;
    }
    @Override
    public String toString() {
        return "Address{" +
                "name='" + name + '\'' +
                ", dog=" + dog +
                ", cat=" + cat +
                '}';
    }
}
  • @Autowired :自动装配通过类型。名字
    如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value=“xxx”)
  • @Nullable 字段标记了这个注解,说明这个字段可以为null;
  • @Resource :自动装配通过名字。类型。
    测试
  @Test
    public void Test8() {
        ApplicationContext context = new ClassPathXmlApplicationContext("myUser2.xml");
        Address add = (Address) context.getBean("address");
        System.out.println(add);
        add.getCat().show();
        add.getDog().show();
    }

6.3 使用注解开发

1.必须要有aop的jar包
2.导入contex约束

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
       http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
     <!--开启注解支持
     context:支持上下文
     annotation-config :注释配置-->
    
    <context:annotation-config/>
   
</beans>

3.编写实体类

@Component("kafa")
public class KaiFa {
    //@Value("熬夜哦")
    public String name;
    @Value("熬夜哦")
    public void setName(String name) {
        this.name = name;
    }
}

测试

    @Test
    public void test9() {
        ApplicationContext context = new ClassPathXmlApplicationContext("ZhuJieKai.xml");
        KaiFa kafa = (KaiFa) context.getBean("kafa");
        System.out.println(kafa.name);
    }

4.衍生的注解

pojo @Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!
dao 【@Repository】
service 【@Service】
controller 【@Controller

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

5.作用域

@Component("kafa")
@Scope("prototpe")//Scope  范围
public class KaiFa {
    //@Value("熬夜哦")
    public String name;
    @Value("熬夜哦")
    public void setName(String name) {
        this.name = name;
    }
}

6.小结

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

2.xml 用来管理bean;
注解只负责完成属性的注入;
我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持

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

7.纯注解开发java,不在需要配置xml文件

这种纯Java的配置方式,在SpringBoot中随处可见

7.1,xml环境搭建

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

</beans>

7.2,编写配置类

@Component  //注入 这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
@Import(Import2.class)//Import 导入配置类联系起来
public class Dog {
    @Value("旺财")
    public String name;
}


//@Configuration 代表这个类是一个配置类
//@Configuration  //等同于Dog.xml
@Configuration
public class ApplicatContext3 {
    //bean 对象
    //方法名就是 bean的具体id
    //返回值就是具体的bean的class
    @Bean
    public Dog dog(){
        return new Dog();
    }
}

7.3,注入

@Component  //注入
@Import(Import2.class)//Import 导入配置类联系起来
public class Dog {
    @Value("旺财")
    public String name;
}

7.4测试

    @Test
    public void test10(){
        //AnnotationConfigApplicationContext 注释配置应用程序上下文
        ApplicationContext context = new AnnotationConfigApplicationContext(ApplicatContext3.class);
        Dog dag = (Dog) context.getBean("dog");
        System.out.println(dag.name);
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值