Spring之DI(注解方式)

2019-09-29  本文已影响0人  紫荆秋雪_文

一、Spring提供的标签

1、Autowired标签

@Autowired:是Spring定义的标签,所以不太稳定,并且对象和spring框架关联;

public void setXxx(OtherBean1 other1,OtherBean2 other2) {}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SPELTest {

    @Autowired
    private ApplicationContext ctx;
}

2、Resource标签

@Resouce:是J2EE的规范,所以稳定,在J2EE规范容器中也能正常使用;

    @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的限制

4:Bean组件版型标签

5:指定bean的作用域@Scope

6:初始化方法和销毁方法

@PostConstruct
  public void init() {
  相当于<bean init-method="init" />

  @PreDestroy
  public void destory() {
  相当于<bean destroy-method="destory" />
上一篇下一篇

猜你喜欢

热点阅读