Spring IoC (二)

Spring IoC(一),对 IoC 有了简单的认识,本篇学习一下 IoC 在 Spring 中是如何使用的。

1. Spring IoC 如何注册托管类型

Spring 提供了两种最常用的注册方式:XML配置文件 和 Annotation 注解。

Annotation 注解是现在最流行的方式,主要是因为通过代码注解的方式直接就可以实现注册,省却了编写 XML 配置文件的繁琐,也避免了错误,而且代码修改了,比如加了参数,也不需要去管理配置文件。

特别是随着微服务的兴起,注解方式也称为了 Spring Boot 和 Spring Cloud 等微服务框架的默认选择。

  • XML配置文件 注册

先编写测试代码:

public class Application {
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("app.xml");
        ServiceA serviceA = context.getBean(ServiceA.class);
        serviceA.print();
    }
}

public class ServiceA {

    private final DomainA1 domainA1;

    public ServiceA(DomainA1 domainA1) {
        this.domainA1 = domainA1;
    }

    public void print() {
        System.out.println("DomainA1 is " + domainA1 == null ? "" : "Not" + " null");
    }

}


public class DomainA1 {
}

在编写配置文件:

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

    <bean id="serviceA" class="com.test.ServiceA">
        <constructor-arg name="domainA1" ref="domainA1"></constructor-arg>
    </bean>
    <bean id="domainA1" class="com.test.DomainA1"></bean>

</beans>

上述配置文件中,每一个 bean 标签代表一个注册类型


  • Annotation 注解

编写测试代码:

public class Application {
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("app.xml");
        ServiceA serviceA = context.getBean(ServiceA.class);
        serviceA.print();
        serviceA.printB();
    }
}


@Component
public class DomainB {
}


public class ServiceA {

    private final DomainA1 domainA1;

    @Autowired
    private DomainB domainB;

    public ServiceA(DomainA1 domainA1) {
        this.domainA1 = domainA1;
    }

    public void print() {
        System.out.println("DomainA1 is " + domainA1 == null ? "" : "Not" + " null");
    }

    public void printB() {
        System.out.println("DomainB is " + domainB == null ? "" : "Not" + " null");
    }

}

这次,我们新增一个 DomainB 的测试类,但是不在 app.xml 文件中添加 bean ,我们看看 DomainB 能否被 IoC 容器实例化:

Not null
Not null

最终输出结果显示,DomainB 被 IoC 容器成功实例化。

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×