spring笔记(三)---------自动装配和注解开发


自动装配

1.环境搭建
建立三个实体类
一个人拥有两只宠物

public class cat {
    public void shout(){
        System.out.println("miao~");
    }
}
public class dog {
    public void shout(){
        System.out.println("wang~");
    }
}
public class person {
    public String name;
    private dog dog;
    private cat cat;

    public String getName() {
        return name;
    }

    public dog getDog() {
        return dog;
    }

    public cat getCat() {
        return cat;
    }
}

byName自动装配
在这里插入图片描述
byType自动装配
在这里插入图片描述
在这里插入图片描述

注解实现自动装配

@Autowired

在这里插入图片描述
在这里插入图片描述

纠正:Autowired默认通过ByType进制自动装配,所以上面最后一句应该为符合类型byType,且该class唯一

在这里插入图片描述

@autowired默认通过bytype方式进行装配,如果一个class有多个实例,则无法直接通过byType装配,转为byName匹配;也可以使用@qualifier()指定名字进行匹配;因此这两个注解一般是配套使用的。

Resource

在这里插入图片描述

@resource是java自带的注解,默认通过byName进行匹配,如果没有对应的byName,则通过byType进行匹配,也可以通过声明name进行匹配

在这里插入图片描述

注解开发

1.注解开发一定要记得在spring配置中导入相关规范

<?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/>
    //去扫描使用了注解的包
    <context:component-scan base-package="com.govd.pojo"/>


</beans>

@component 表示将该类注册成bean,id默认为该类名的小写
@value 在类中的属性上可以用这个属性进行赋值
@scope 作用域
@autowored 自动装配

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

纯Java注解方式配置spring

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

@configuration本质也是一个@component,可以理解为new annotationApplicationContext的时候封装成了原来applicationContext.xml中的一部分配置,@bean就相等原来在配置文件中注册bean,方法名就是id,返回类型就是class.
@component-scan和原来使用道理是一样的,去扫描其他标有@component的类注册成bean
@import也是一样的道理,只不过从导入.xml变成了.class

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值