一、Spring提供的标签
1、Autowired标签
@Autowired:是Spring定义的标签,所以不太稳定,并且对象和spring框架关联;
- 通过@Autowired标签可以让Spring自动的把属性需要的对象从Spring容器找出来,并注入给该属性
- Spring3.0之前,需要手动配置@Autowired解析注解程序,Spring就会自动的加入针对@Autowired标签的解析程序。从Spring3.0开始,可以不再需要改配置了
- @Autowired标签要贴在字段或者setter方法上
- @Autowired可以同时为一个属性注入多个对象
public void setXxx(OtherBean1 other1,OtherBean2 other2) {}
- 使用@Autowired标签可以注入Spring内置的重要对象,比如:BeanFactory,ApplicationContext
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SPELTest {
@Autowired
private ApplicationContext ctx;
}
- 默认情况下@Autowired标签必须要能找到对应的对象,否则报错。但是可以通过使用required=false来避免该问题:@Autowired(required = false)
-
- @Autowired找bean的方式
- 1> 首先按照 [依赖对象的类型] 找,如果找到则使用setter方法或者字段直接注入
- 2> 如果在Spring上下中找到多个匹配的类型,再按照名字去找,如果没有匹配则报错
- 3> 可以通过使用@Qualifier("otherBean")标签来规定依赖对象按照bean的id+类型去找
2、Resource标签
@Resouce:是J2EE的规范,所以稳定,在J2EE规范容器中也能正常使用;
- @Resource标签是J2EE规范的标签
- @Resouce标签也可以作用于字段或者setter方法
- 也可以使用@Resouce标签注入一些Spring内置的对象,如BeanFactory、ApplicationContext
- @Resouce必须要求有匹配的对象
- <context:annotation-config>既引入了@Autowired标签的解析器,也引入了@Resource的解析器
-
- @Resource标签找bean的方式
- 1> 首先按照名字去找,如果找到,就使用setter或者字段注入
- 2> 如果按照名字找不到,再按照类型去找,但是如果找到多个匹配类型,报错
- 3> 可以直接使用name属性指定bean的名称,但是,如果指定的name,就只能按照name去找,如果找不到,就不会再按照类型去找
@Resource(name="otherBean2")
private OtherBean2 other2;
等价于
@Autowired
@Qualifier("otherBean2")
private OtherBean2 other2;
二、IoC之注解
1:使用标签来完成IoC,就必须有IoC标签的解析器,使用context:component-scan来扫描Spring需要管理的bean。base-package就告诉Spring,去哪些包及其子包里扫描bean,如果有多个包需要被扫描,只需要用逗号隔开多个包即可(不推荐)<context:component-scan base-package="com.revanwang.." />
2:标签Bean的注解:@Component,默认情况,直接使用类的名字(首字母小写作为bean的名字)。如果要修改bean的名称,直接使用value属性来重新定义bean的名称
@Component("otherbean")
public class OtherBean {}
3:使用@Component的限制
- 不能运用到静态工厂方法和实例工厂方法,但是可以使用到FactoryBean
- 对于没有源代码的类(框架内部的预定义类),只能用XML配置;
4:Bean组件版型标签
- @Service用于标注业务层组件、
- @Controller用于标注控制层组件(如struts中的action)
- @Repository用于标注数据访问组件,即DAO组件。
- @Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
5:指定bean的作用域@Scope
- 默认是单例
- @Scope("prototype")
6:初始化方法和销毁方法
@PostConstruct
public void init() {
相当于<bean init-method="init" />
@PreDestroy
public void destory() {
相当于<bean destroy-method="destory" />
网友评论