Spring5—IOC控制反转、注解开发

目录

1、Spring5—IOC控制反转

2、Spring5—注解开发


1、Spring5—IOC控制反转

↓↓↓看一段简单的代码先↓↓↓

public class ClassPathXmlApplicationContext{
    private static Map<String,Object> beanMap = new HashMap<>();
    private String filePath;
    public ClassPathXmlApplicationContext(String filePath){
        this.filePath = filePath;
        load();
    }
    
    private void load(){
        tyr{
            String path= ClassPathXmlApplicationContext.class.getClassLoader().getResource(filePath).getPath();
            path = URLDecoder.decode(path,"utf-8");
            Document document = Jsoup.parse(new File(path),"utf-8");
            Elements beans = document.getElementsByTag("bean");
            
            if(beans!=null && beans.size() > 0){
                for(int i = 0;i<beans.size();i++){
                    //遍历所有的bean标签
                    Element bean = beans.get(i);
                    //获取bean标签中的class和id值
                    String className = bean.attr("class");
                    String id = bean.attr("id");
                    //通过反射创建对应类的对象
                    Class<?> clazz = Class.forName(className);
                    Constructor<?> constructor = clazz.getConstructor();
                    Object obj = constructor.newInstance();
                    //把id作为key创建出来的对象作为value存进map中
                    beanMap.put(id,obj);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    //根据id从容器中获取对应的对象
    public Object getBean(String id){
        return beanMap.get(i);
    }
}

这段代码的原理:把全类名和id配置在beans.xml文件中,然后ClassPathXmlApplicationContext容器会读取这个beans.xml配置文件,通过反射去创建全类名的对象,把id作为key和发射创建出来的对象作为value存进beanMap中,我们要使用的时候通过getBean()方法传入id,就能获取到对应的对象啦,简单地实现了解耦。

Spring的IOC原理也是如此,控制反转,之前对象的控制权在类手上,我们要亲自去new出来,现在反转后到了Spring容器手上。

Bean的常用属性配置:

  1. id:bean的唯一标识,同一个Spring容器中不允许重复

  2. class:全类名,用于反射创建对象

  3. scope:singleton和prototype

    设置为singleton则一个容器中只会有这一个bean对象,默认容器创建的时候就会创建该对象。

    设置为prototype则一个容器中会有多个该bean对象,每次调用getBean方法获取时都会创建一个新对象。

  4. DI依赖注入

    依赖注入可以理解成IOC的一种应用场景,反转的是对象间依赖关系维护权。

    set方法注入

    在要注入属性的bean标签中进行配置,前提是该类有提供属性对应的set方法

    <bean class="com.baidu.domain.cat" id="cat">
        <property name="name" value="tom"></property>
    </bean>
    <bean class="com.baidu.domain.Student" id="student">
        <property name="name" value="张三"></property>
        <property name="age" value="20"></property>
        <property name="cat" ref="cat"></property>
    </bean>

    有参构造注入

    在要注入属性的bean标签中进行配置,前提是该类有提供对应的有参构造方法

     

    <bean class="com.baidu.domain.Student" id="student">
        <constructor-arg name="name" value="张三"></constructor-arg>
        <constructor-arg name="id" value="12"</constructor-arg>
        <constructor-arg name="age" lue="8">/constructor-arg>
        <constructor-arg name="dog" ref="dog">/constructor-arg>
    </bean>

    复杂类型属性注入

    ......

配置文件

  1. 读取properties文件

    我们可以让Spring读取properties文件中的key/value,然后使用其中的值。

    设置读取properties

    在Spring配置文件中加入如下标签:指定要读取的文件的路径

    <context:property-pllaceholder location="classpath:filename.properties">

    其中的classpath表示类加载路径下

    我们也会用到如下写法:classpath:*.properties其中的 *表示文件名任意。

    使用配置文件中的值

    在我们需要使用的时候可以使用$(key)来表示具体的值,注意要在value属性中使用才可以,如:

    <property name="propertyName" value = "${key}">

  2. 引入Spring配置文件

    我们可以在主的配置文件中通过import标签的resource属性,引入其他的xml配置文件

    <import resource="classpath:applicationContext-book.xml">

2、Spring5—注解开发

  1. 注解开发

    为了简化配置,Spring支持使用注解代替xml配置。

  2. Sring常用注解

    如果要使用注解开发必须要开启组件扫描,这样加了注解的类才会被识别出来,Spring才能去解析其中的注解

    <context:component-scan base-package="com.baidu">

  3. IOC相关注解

    @component

    @Controller

    @Service

    @Repository

    4个 注解都是加到类上的

    他们都可以起到类似bean标签的 作用,可以吧加了改注解的类的对象放入Spring容器中。

    实例在使用时选择任意一个都可以,但是后3个注解是语义化注解。

    如果是Service类要求使用@Service

    如果是Dao类要求使用@Repository

    如果是Controller类要求使用@Controller

    如果其他类可以使用@Component

  4. DI相关注解

    如果一个bean已经放入Spring容器中了,那么我们可以使用下列注解实现属性注入,让Spirng容器帮我们完成属性的赋值

    1. @Value

      主要用于String,Integer等可以直接赋值的属性注入,不依赖setter方法,支持SpEL表达式。

    2. @AutoWired

      Spring会给加了该注解的属性自动注入数据类型相同的对象注入。

    3. @Qualifier

      如果相同类型的bean在容器中有多个时,单独使用@AutoWired就不能满足要求,这时候可以在加上@Qualifier来指定bean的名字从容器中获取bean注入。

      (注意:该注解不能单独使用,一般搭配@AutoWired+@Qualifier一起使用才有效)

  5. XML配置文件相关注解

    1. @Configuration

      标注在类上,表示当前类是一个注解类。我们可以用注解类来完成替换掉XML配置文件。

      注意:如果使用配置类替换了XML配置,Spring容器要使用:AnnotationConfigApplicationContext

      @Configuration
      public class ApplicationConfig{
          
      }

    2. @ComponentScan

      可以使用代替context:component-scan标签来配置组件扫描。

      (注意:需要指定包)

      @ComponentScan(basePackets = "com.baidu")
      public class ApplicationConfig{
          
      }

    3. @Bean

      可以用来代替bean标签,主要用于第三方类的注入。

      (注意:如果同一种类型的对象在容器中只有一个,可以不设置爱bean的名称)

      @Configuration
      @ComponentScan(basePackets = "com.baidu")
      public class ApplicationConfig{
          
          //@Bean("dataSource")
          @Bean
          public DataSource getDataSource(){
              xxx
              xxx
              return DataSource;
          }
      }

    4. PropertySource

      可以用来代替context:property-placeholder,让Spring读取指定的properties文件。

      然后可以使用@Value("${xxx.xxx.xxx}")来获取 读取的值。


      最后如何选择使用XML还是注解开发:

      1. SSM---项目中的类IOC和DI都使用注解,对第三方jar包中的类,配置组件扫描时使用xml进行配置。

      2. SpringBoot---纯注解开发。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网农民工001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值