3、IOC创建对象的方法


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

  • 使用有参构造创建对象

    • 下标赋值
    <!--第一种  下标赋值-->
        <bean id="user" class="com.jan.pojo.User">
          <constructor-arg index="0" value="钟健"/>
        </bean>
    
    • 类型创建

      <!--第二种   通过类型创建  不建议使用-->
          <bean id="user" class="com.jan.pojo.User">
              <constructor-arg type="java.lang.String" value="zhongjian"/>
          </bean>
      
    • 参数名

      <!--   第三种  直接通过参数名来设置-->
          <bean id="user" class="com.jan.pojo.User">
              <constructor-arg name="name" value="Jan"/>
          </bean>
      

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

4、Spring配置


4.1、别名

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

4.2、Bean的配置

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

4.3、import

  • 这个import一般用于团队开发使用,他可以将多个配置文件导入合并为一个,假设,现在项目有对人开发,将三人不同的开类需注册到不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!

  • 张三

  • 李四

  • 王五

  • applicationContext

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

5、依赖注入


5.1、构造器注入

  • 依赖注入:
    • 依赖: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.jan.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. 完善注入信息

    <?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="address" class="com.jan.pojo.Address">
            <property name="address" value="北京"/>
        </bean>
    
        <bean id="student" class="com.jan.pojo.Student">
            <!--第一种,普通注入,value-->
            <property name="name" value="钟健"/>
            <!--第二种,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="111111222222223333"/>
                    <entry key="银行卡" value="123456789"/>
                </map>
            </property>
    
            <!--Set-->
            <property name="games">
                <set>
                    <value>LOL</value>
                    <value>COS</value>
                </set>
            </property>
    
            <!--null-->
            <property name="wife">
                <null/>
            </property>
    
            <!--Properties-->
            <property name="info">
                <props>
                    <prop key="driver">20230102</prop>
                    <prop key="url">男</prop>
                    <prop key="username">root</prop>
                    <prop key="password">123456</prop>
                </props>
            </property>
    
        </bean>
    
    </beans>
    

5.2、Set方式注入【重点】

5.3、扩展方式注入

我们可以使用P命名空间和C 命名空间进行注入

  • 官方解释

    image-20230310215510523

  • 使用

    <?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: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">
    
         <!-- P命名空间注入,可以直接注入属性的值   property-->
        <bean id="user" class="com.jan.pojo.User" p:name="钟健" p:age="18"/>
    
        <!-- c命名空间注入,通过构造器注入   construct-args-->
        <!--在User类中要有无参和有参构造器才可以使用 C 命名注入-->
        <bean id="user2" class="com.jan.pojo.User" c:age="18" c:name="Jan"/>
        
        
    </beans>
    
  • 测试

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

注意点: P 命名和 C 命名空间不能直接使用,需要导入xml约束!

  • P命名注入
xmlns:p="http://www.springframework.org/schema/p"
  • C命名注入
xmlns:c="http://www.springframework.org/schema/c"

5.4、bean的作用域

image-20230310224450196

  1. 单例模式(Spring默认机制)--->30分钟的教学记得看

    • 有时候并发情况下会产生延迟或数据不一致,单线程一般用这个
     <bean id="user2" class="com.jan.pojo.User" c:age="18" c:name="Jan" scope="singleton"/>
    
  2. 原型模式:每次从容器中get的时候,都会产生一个新对象!

     <bean id="user2" class="com.jan.pojo.User" c:age="18" c:name="Jan" scope="prototype"/>
    
    • 别特浪费资源,多线程可以使用原型模式
  3. 其余的request、session、application,这些个只能在web开发中使用的!

6、Bean的自动配置

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

在spring的三种配置方式:

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

6.1、测试

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

  • 原来的xml配置
    <bean id="cat" class="com.jan.pojo.Cat"/>
    <bean id="dog" class="com.jan.pojo.Dog"/>

    <bean id="people" class="com.jan.pojo.People">
        <property name="name" value="钟健"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>

6.2、ByName自动装配

<bean id="cat" class="com.jan.pojo.Cat"/>
<bean id="dog" class="com.jan.pojo.Dog"/>
<!--
    ByName: 会自动在容器上下文中查找,和自己对象set方法后面的值对应的 bean id!
    ByType: 会自动在容器上下文中查找,和自己对象属性类型相同的 bean !
    -->
<bean id="people" class="com.jan.pojo.People" autowire="byName">
    <property name="name" value="钟健"/>

</bean>

6.3、ByType自动装配

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

</bean>

小结:

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

6.4、使用注解实现自动装配

jdk1.5支持的注解,Spring2.5就支持注解了!

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

要使用注解须知:

  • 导入约束。context约束
  • 配置注解支持: 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"
    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!

科普:

@Nullable 字段标记了这个注解,说明了这个字段可以为null;
public People(@Nullable String name) {
this.name = name;
}

public @interface Autowired {
    boolean required() default true;
}

测试代码

public class People {

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

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

public class People {


    @Autowired
    @Qualifier(value = "cat222")
    private Cat cat;
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;
}

xml的代码
    
    <bean id="cat222" class="com.jan.pojo.Cat"/>
    <bean id="cat111" class="com.jan.pojo.Cat"/>
    <bean id="dog222" class="com.jan.pojo.Dog"/>
    <bean id="dog111" class="com.jan.pojo.Dog"/>
    <bean id="people" class="com.jan.pojo.People" />

@Resource注解

public class People {

    @Resource(name = "cat2")
    private Cat cat;
    @Resource
    private Dog dog;
}

小结:

@Autowired和@Resource的区别:

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

7、使用注解开发


在Spring4之后,要使用注解开发,必须要保证aop包的注入!

image-20230311213536850

使用注解需要导入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. 属性如何注入

    //等价于 <bean id="user" class="com.jan.pojo.User"/>
    //@Component 组件
    @Component
    public class User {
    
        public  String name ;
    
        //相当于 <property name="name" value="zhongjian"/>
        @Value("zhongjian")
        public void setName(String name) {
            this.name = name;
        }
    }
    
  3. 衍生的注解

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

    • dao 【@Repository】

    • service 【@Service】

    • controller 【@Controller】

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

  4. 自动装配置

    - @Autowired:自动装配,通过属性,名字
         如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value == "xxx")
    - @Nullable 字段标记了这个注解,说明了这个字段可以为null;
    - @Resource:自动装配,通过名字,属性
    
  5. 作用域

    @Scope("prototype")
    @Scope("singleton")
    
    @Component
    @Scope("prototype")
    public class User {
    
        public  String name ;
    
        //相当于 <property name="name" value="zhongjian"/>
        @Value("zhongjian")
        public void setName(String name) {
            this.name = name;
        }
    }
    
  6. 小结

    xml与注解:

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

    xml与注解最佳实践:

    • xml用来管理bean;

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

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

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

8、使用Java的方式配置Spring


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

JavaConfig 是 Spring 的一个字项目,在 Spring 4之后, 它成为了一个核心功能!

image-20230311230015611

实体类

package com.jan.pojo;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
@Component
public class User {
    private  String name;

    public String getName() {
        return name;
    }

    @Value("ZHONGJIAN")  //属性注入值
    public void setName(String name) {
        this.name = name;
    }

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

配置文件

package com.jan.config;

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

//这个也是Spring容器托管,注册到容器中,因为它本来就是一个@Component
//@Configuration代表这是一个配置类,就和 我们之前看到的beans.xml
@Configuration
@ComponentScan("com.jan.pojo")
@Import(JanConfig2.class)
public class JanConfig {


    //注册一个Bean,就相当于我们之前写的一个bean标签
    //这个方法的名字(eg:user),就相当于bean标签中的id属性
    //这个方法的返回值(eg:User),就相当于bean标签中的class属性
    @Bean
    public User user(){
        return new User(); // 就是返回要注入到bean的对象!
    }

}

测试类

public class MyTest {
    public static void main(String[] args) {


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

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