Spring中bean的AutowireMode(自动装配模型)和自动装配技术

LD is tigger forever,CG are not brothers forever, throw the pot and shine forever.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code,Keep progress,make a better result.
Survive during the day and develop at night。

目录

概述

Spring中bean的AutowireMode(自动装配模型)和自动装配技术

实现思路分析

1.Spring 注入的方式

spring注入方式有两种: 1 通过set方法 2 通过构造函数(如果有多个构造函数会选择参数多的构造方法)

@Resource: 默认是通过name来查找注入值,如果不存在就报错
@Autowired 通过类型查找(类型),然后再通过name
AutowireMode(自动装配模型):在spring中有四种模式分别是:
1 autowire_no(0): 默认装配模式, 目前非xml配置都是使用这种方式,然后程序员使用注解手动注入
2 autowire_name: 通过set方法,并且 set方法的名称需要和bean的name一致 byName

3 autowire_type: 通过set方法,并且再根据bean的类型,注入属性,是通过类型配置 byType
4 autowire_construcor: 通过构造器注入

demo:

1 首先自定义一个bean注册器,用来设置bean属性的注入方式
public class MyImportBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		GenericBeanDefinition son = 
        (GenericBeanDefinition)registry.getBeanDefinition("son");
         //设置装配模型
		//设置auto类型: AUTO_NO 默认是程序要经常加的 @Autowried或者@Resource
        //设置Son这个类的属性注入方式为默认类型
		son.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_NO);
		registry.registerBeanDefinition("son",son);
 
	}
}
 
2 定义Son这个类
public class Son {
 
	//不做任何处理,这个时候很明显Son对象里面student是空的
	private  Student student;
 
	public Student getStudent() {
		return student;
	}
 
	public void setStudent(Student student) {
		this.student = student;
	}
}
 
3 测试类:
public class Test {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new 
        AnnotationConfigApplicationContext();
		applicationContext.register(MyBean.class);
		applicationContext.register(Appconfig.class);
		applicationContext.refresh();
 
		/*  1 不加 @Autowired或者@Resource 不做特殊处理
		 *   下面这对象会为空
		 *   2 写个类实现ImportBeanDenitionRegester, 设置Son属性的注入方式 
            MyImportBeanDefinitionRegister
		 *
		 *
		 * */
		System.out.println("==="+applicationContext.getBean(Son.class).getStudent());
 
	}
}
 

相关工具如下:

分析:

小结:

主要讲述了一些Spring 注入设计,里面有许多不足,请大家指正~

参考资料和推荐阅读

1.链接: 参考资料.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

执于代码

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

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

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

打赏作者

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

抵扣说明:

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

余额充值