spring学习—AnnotationConfigApplicationContext的初始化

概述

我们在使用spring framework的过程中,使用最广泛的spring容器的方式就是使用注解。我们有两种方式初始化ApplicationContext(就是spring的IoC容器)。

基于XML的方式

1、定义一个xml配置文件(src/main/resources/application.xml),如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <!-- 指定需要扫描的所有srping bean所在的包的包名 -->
    <context:component-scan base-package="com.dokbok.hsfw"/>
</beans>

2、编写提供服务spring bean

@Component
public class HelloUtils {
    public String getUUID(){
        return UUID.randomUUID().toString();
    }
}

3、编写测试代码

public class HelloApplication {
    public HelloApplication(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml");

        HelloUtils helloUtils = ctx.getBean(HelloUtils.class);
        System.out.print(helloUtils.getUUID());
    }

    public static void main(String[] args) {
        new HelloApplication();
    }
}

基于编程的方式

1、编写提供服务spring bean

@Component
public class HelloUtils {
    public String getUUID(){
        return UUID.randomUUID().toString();
    }
}

2、编写激活及测试代码

public class HelloApplication {
    public HelloApplication(){
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.scan(HelloApplication.class.getPackage().getName());
        ctx.refresh();

        HelloUtils helloUtils = ctx.getBean(HelloUtils.class);
        System.out.print(helloUtils.getUUID());
    }

    public static void main(String[] args) {
        new HelloApplication();
    }
}

上述代码指定了AnnotationConfigApplicationContext类的对象扫描当前类HelloApplication 所在包,将其下使用spring bean注解的类进行容器化管理。其实我们也可以手动向容器中注册spring bean,代码如下:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(HelloUtils.class);
ctx.refresh();

HelloUtils helloUtils = ctx.getBean(HelloUtils.class);
System.out.print(helloUtils.getUUID());

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注