spring5整理:(二)DI注解

15 篇文章 0 订阅

目录

一.Autowited注解

二.Resource

三.@Value注解


一.Autowited注解

spring规范提供

1.可以让spring自动的把属性需要的对像找出来,并注入到对像

2.可以贴字段或者setter方法上面

3.可以同时注入多个对象

@Autowired
public void setter(SomeBean b1,SomeBean b2){
}

4.可以注入一些spring内置的重要对象,比如BeanFactory,ApplicationContext,ServletContext等

5.默认情况下Autowired注解必须要能找到对应的对象,否则报错,通过required=false来避免这个问题

   @Autowired(requied=false)

6.注解解析器,spring3.0之前,需要手动配置Autowired注解的解析程序,在Web开发中必须配置

  <context:annotation-config>

7.Autowired注解寻找bean的方式:

  1)首先按照依赖对象的类型找,如果找到,就是用setter方法或者字段直接注入

   2)如果在spring上下文中找到多个匹配的类型,再按照名字找,如果没有匹配报错;

   3)可以通过使用@Qualifier("other")标签来规定依赖对象按照bean的id和类型的组合方式去找

<context:annotation-config/>
<bean id="otherBean1" id="com.bigfong.OtherBean">
<bean id="otherBean2" id="com.bigfong.OtherBean">


@Autowired
@Qualifier("otherBean1")
private OtherBean  other1;

@Autowired
@Qualifier("otherBean2")
private OtherBean  other2;

@Setter注解贴在字段上面,仅仅是为我们生成一个Setter方法,本身不能完成注入操作

DI注解分:

1.spring官方注解,如Autowired, 

2.JavaEE规范:Resource;

两者功能类似,并且都需要配置DI注解解析器:<context:annotation-config/>

 

二.Resource

与Autowired不同点:

1.必须要找到对象

2.首先按照名字找,如果找到就使用setter或字段注入,如果按名字找不到,再按照类型去找,如果找到多个匹配则报错

3.可以直播使用name属性指定bean的名称(@Resource(name="xxx"));但是如果指定的name,就只能按name找,如果找不到,就不会再按照类型去找

<context:annotation-config/>
<bean id="someBean" id="com.bigfong.SomeBean">
<bean id="otherBean1" id="com.bigfong.OtherBean">
<bean id="otherBean2" id="com.bigfong.OtherBean">


@Resource
private SomeBean someBean;

@Resource(name="otherBean1")
private OtherBean  other1;

@Resource(name="otherBean2")
private OtherBean  other2;

注入类型对应注解选择

常量类型:        xml中:value       java代码中:@Value

对象类型:        xml中:ref           java代码中:@Autowired/@Resource

三.@Value注解

  server.properties内容

server.port=8888

spring-context.xml

<!--加载properties文件-->
<context:property-placeholder location="classpath:db.properties,classpath:server.properties">

可以写为以下
<context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true">
<context:property-placeholder location="classpath:server.properties" ignore-unresolvable="true">

java代码:

@Value("${server.port}")
private int port;

 

IOC和DI其实是一个东西:

IOC:字面上,更多强调的是spring帮我们创建对像

DI:字面上,spring不仅帮我们创建对象,还要为该对象设置依赖的数据

 

上一篇:spring5整理:(一)Ioc和DI 

下一篇:spring5整理:(三)IOC注解 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值