目录
一.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不仅帮我们创建对象,还要为该对象设置依赖的数据