spring学习(一)什么是spring context

2,732 阅读2分钟

spring context

学习spring有必要先了解spring的上下文是什么,因为spring的一切都是从这开始的。

理解spring context

org.springframework.context.ApplicationContext 接口表示Spring IoC容器,负责实例化、配置和组装bean。容器通过读取配置元数据获取关于要实例化、配置和组装哪些对象的指令。 配置元数据用XML、Java注释或Java代码表示。它允许您表达组成应用程序的对象以及这些对象之间丰富的相互依赖关系。

Spring提供了ApplicationContext接口的几个实现。在独立应用程序中,通常创建ClassPathXmlApplicationContext或FileSystemXmlApplicationContext的实例。

在大多数应用程序场景中,不需要显式用户代码来实例化Spring IoC容器实例。例如,在web应用程序场景中,在应用程序的web. XML文件中使用简单的8行web描述符XML就足够了。

spring-ioc-container.png

Configuration Metadata 注入到spring container

如上图所示,Spring IoC容器使用一种形式的配置元数据。此配置元数据表示作为应用程序开发人员,您如何告诉Spring容器实例化、配置和组装应用程序中的对象。 通常用下面这两种方式声明。

  • xml配置文件。
  • 使用@Configuration注释的java类。

怎么注入实例

注入实例的几个常见注解:

@Bean

注释在方法上,标记这个方法的返回值作为一个被spring容器管理的对象。

@Configuration

被@Configuration注释的java类表示这个类用于Bean资源定义。

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

用 Java-based configuration的方式创建spring container

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    MyService myService = ctx.getBean(MyService.class);
    myService.doStuff();
}

AnnotationConfigApplicationContext并没有限定只能使用@Configuration的注释类实例化,它可以使用任何被@Component or JSR-330注释的类,例如:

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(MyServiceImpl.class, Dependency1.class,Dependency2.class);
    MyService myService = ctx.getBean(MyService.class);
    myService.doStuff();
}

@ComponentScan

允许spring扫描指定的目录下被@Component注释的类

@Configuration
@ComponentScan(basePackages = "com.acme")public class AppConfig {
...
}

把你的业务对象注入到 spring container

使用@Component注解,注释java类 @Controller,@Service,@Repository被@Component注解注释过,也会被spring作为@Component注解处理

使用spring bean

通过@Autowired为method,field,装配容器中的bean

参考文档

docs.spring.io/spring-fram…