前言

ApplicationContext是Spring应用程序中的中央接口,由于继承了多个组件,使得ApplicationContext拥有了许多Spring的核心功能,如获取bean组件,注册监听事件,加载资源文件等。ApplicationContext接口定义如下:

public interface ApplicationContext extends 
		EnvironmentCapable, 
		ListableBeanFactory, 
		HierarchicalBeanFactory,
		MessageSource, 
		ApplicationEventPublisher, 
		ResourcePatternResolver{}
  • EnvironmentCapable:获取运行时环境
  • ListableBeanFactory:获取beanNames的功能
  • HierarchicalBeanFactory:获BeanFactory的功能
  • MessageSource:集成消息解析器
  • ApplicationEventPublisher:事件监听
  • ResourcePatternResolver:资源解析器

一、@Autowired(@Resouce)注入

@Component
public class ApplicationContextProvider1 {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean("user01")
    public User user(){
        return new User("zhangsan",18);
    }

    @Bean("printApplicationContext01")
    public void printApplicationContext(){
        System.out.println(applicationContext.getBean("user01"));
    }
}

二、实现ApplicationContextAware接口(推荐)

@Component
public class ApplicationContextProvider2 implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean("user02")
    public User user(){
        return new User("lisi",19);
    }

    @Bean("printApplicationContext02")
    public void printApplicationContext(){
        System.out.println(applicationContext.getBean("user02"));
    }
}

三、构造器方法注入

利用Spring4.3特性

  • 构造函数只能有一个,如果有多个,就必须有一个无参数的构造函数,此时,Spring会调用无参数的构造函数
  • 构造函数的参数,必须在Spring容器中存在
@Component
public class ApplicationContextProvider3 {

    private ApplicationContext applicationContext;

    public ApplicationContextProvider3(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean("user03")
    public User user(){
        return new User("wangwu",20);
    }

    @Bean("printApplicationContext03")
    public void printApplicationContext(){
        System.out.println(applicationContext.getBean("user03"));
    }
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐