Spring Bean如何实现自动配置代码实例

网友投稿 253 2022-11-24


Spring Bean如何实现自动配置代码实例

自动装配是Spring满足Bean依赖的一种方式;

Spring会在context中自动寻找,并自动给bean装配属性;

在Spring中有三种装配的方式:

在xml中显式配置

在java中显式配置

隐式的自动装配bean(重要)

测试

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

byName自动装配

byType自动装配

小结:

byname,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致;

byType,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致;

使用注解实现自动装配

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

要使用注解须知:

导入约束:context约束

配置注解的支持:context:annotation-config/

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="http://springframework.org/schema/beans

https://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context

https://springframework.org/schema/context/spring-context.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="http://springframework.org/schema/beans

https://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/context

https://springframework.org/schema/context/spring-context.xsd">

@Autowired

直接在属性上使用即可! 也可以在set方法上使用!

使用Autowired我们可以不用编写Set方法,前提是自动装配的属性在IOC容器中存在,且符合名字byname!

补充:

@Nullable

//字段标记了这个注解,说明这个字段可以为null

public @interface Autowired {

boolean required() default true;

}

@Autowired(required = false)

//如果显式定义了require为false,那么这个属性可以为null,否则不能为空

测试代码:

public class People {

@Autowired

private Cat cat;

@Autowired

private Dog dog;

private String name;

}

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解完成时,我们可以使用@Qualifier(value="xxx")去配合使用,xxx是唯一的bean对象id。

public class People {

@Autowired

private Cat cat;

@Autowired

//可以显式的定义装配的对象

@Qualifier(value = "dog")

private Dog dog;

private String name;

}

@Resource注解

public class People {

@Resource(name="cat")

private Cat cat;

@Autowired

//可以显式的定义装配的对象

@Qualifier(value = "dog")

private Dog dog;

private String name;

}

小结:

@Resource和@Autowired的区别:

都是用来自动装配的,都可以放在属性字段上;

@Autowired先byType再byName的方式(常用)

@Resource先byName再byType的方式(常用)


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:idea上提交项目到gitee 最后出现 Push rejected的问题处理方法
下一篇:使用Java方法配置Spring代码解析
相关文章

 发表评论

暂时没有评论,来抢沙发吧~