Spring中IoC - 两种ApplicationContext加载Bean的配置

说明:Spring IoC其实就是在Service的实现中定义了一些以来的策略类,这些策略类不是通过 初始化、Setter、工厂方法来确定的。而是通过一个叫做上下文的(ApplicationContext)组建来加载进来的。这里介绍两种Context组建的构件过程

前提条件:在Gradle工程的build.gradle文件中引入对Spring framework 的支持

repositories {
    mavenCentral()
}

dependencies {
    compile group: ‘org.springframework‘,name: ‘spring-context‘, version: ‘4.1.5.RELEASE‘
    compile group: ‘org.springframework‘,name: ‘spring-core‘, version: ‘4.1.5.RELEASE‘
    testCompile group: ‘junit‘, name: ‘junit‘, version: ‘4.11‘
}
  1. 第一种方式:AnnotationConfigApplicationContext类加载JavaClass File的配置文件

配置文件JavaClass如下:

@Configuration:表示这是一个配置文件

@Bean: 表示这是一个Bean(名字为方法名),将来他要用来与Service中的@Autowired属性配对,注意配对的时候是根据返回类型来对应的,也就是说所有的Service中但凡有@Autowired的属性,他们都是从这个配置文件中拿到的。

@Configuration
public class ApplicationContextConfiguration {
    @Bean
    public AccountRepoisitory accountRepoisitory() {
        return new AccountRepositoryImp();
    }

    @Bean
    public TransactionService transactionService() {
        return new TransactionServiceImp();
    }

    @Bean
    public TransferService transferService() {
        return new TransferServiceImp();
    }
}

再来看一下使用@AutoWired的Service类。这个AutoWired将与上面配置文件中的@Bean结成一对儿

public class TransactionServiceImp implements TransactionService {

    @Autowired
    public  AccountRepoisitory accountRepoisitory;
    @Override
    public void NewTransaction(String accountId1, String accountId2, double money) {
        Account account1=accountRepoisitory.GetAccountByAccountId(accountId1);
        Account account2=accountRepoisitory.GetAccountByAccountId(accountId2);
        Transaction transaction=new Transaction(){ };
        transaction.fromAccount=account1;
        transaction.toAccount=account2;
        transaction.moneyTransfered=money;
        transaction.transactionDate= Calendar.getInstance().getTime();

        BankFactory.Transactions.add(transaction);
    }
}

最后来看Main函数是如何将配置文件与Service文件结合在一起的。 很简单

  ApplicationContext context=
                new AnnotationConfigApplicationContext(
                        com.ctrip.configuration.ApplicationContextConfiguration.class
                );

// 接下来我们就可以使用任何Service中定义的方法了
AccountRepoisitory accountRepoisitory=context.getBean("accountRepoisitory",        AccountRepositoryImp.class);

TransactionService transactionService=context.getBean("transactionService",        TransactionServiceImp.class);

TransferService transferService=context.getBean("transferService",        TransferServiceImp.class        );transferService.Transfer("1","2",234);
 
  1. 第二种方式:通过ClassPathXmlApplicationContext加载xml配置文件

首先是在resources/META-INFO/Config下面新建一个Beans definition 的xml如下(注意这个地址至今我也不理解,放在其他的目录下老失败。好吧先mark了)

Property中定义了每个Bean中涉及的Property。 注意这个地方因为是对属性的赋值,所以在你的Service类中必须支持Setter方法

<?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="accountRepoisitory" class="com.ctrip.depends.AccountRepositoryImp"></bean>
              <bean id="transactionService" class="com.ctrip.depends.TransactionServiceImp">
                     <property name="accountRepoisitory" ref="accountRepoisitory"></property>
              </bean>
              <bean id="transferService" class="com.ctrip.depends.TransferServiceImp">
                     <property name="accountRepoisitory" ref="accountRepoisitory"></property>
                     <property name="transactionService" ref="transactionService"></property>
              </bean>
</beans>

在Main方法中使用其实也很简单

    ApplicationContext context=new ClassPathXmlApplicationContext("classpath:/META-INF/config/application-context.xml");
        Transfer(context);

//通过以上的步骤我们告诉了每个Service的存在和他们所依赖的Service,接下来可以使用任何Service中的方法了
AccountRepoisitory accountRepoisitory=context.getBean("accountRepoisitory",        AccountRepositoryImp.class);

TransactionService transactionService=context.getBean("transactionService",        TransactionServiceImp.class);

TransferService transferService=context.getBean("transferService",        TransferServiceImp.class        );transferService.Transfer("1","2",234);
 
时间: 2024-08-09 06:34:14

Spring中IoC - 两种ApplicationContext加载Bean的配置的相关文章

两种动态加载JavaScript文件的方法

两种动态加载JavaScript文件的方法 第一种便是利用ajax方式,第二种是,动静创建一个script标签,配置其src属性,经过把script标签拔出到页面head来加载js,感乐趣的网友可以看下 动态加载script到页面大约有俩方法 第一种便是利用ajax方式,把script文件代码从背景加载到前台,而后对加载到的内容经过eval()实施代码.第二种是,动静创建一个script标签,配置其src属性,经过把script标签插入到页面head来加载js,相当于正在head中写了一个<sc

unity 3D里有两种动态加载机制

unity 3D里有两种动态加载机制: 一是Resources.Load: 一是通过AssetBundle: 其实两者本质上没有什么区别.Resources.Load就是从一个缺省打进程序包里的AssetBundle里加载资源,而一般AssetBundle文件需要你自己创建,运行时动态加载,可以指定路径和来源的.其实场景里所有静态的对象也有这么一个加载过程,只是Unity后台替你自动完成了. 1.    AssetBundles是什么? 在一些大型的网络游戏,或者加载比较多的一些场景时,如果要等

两种页面加载等待效果的实现

第一种,当打开一个新的页面时,这个页面的加载时间可能会比较长,可以用以下js实现页面等待效果,将该js导入加载的页面即可使用 //获取浏览器页面可见高度和宽度 var _PageHeight = document.documentElement.clientHeight, _PageWidth = document.documentElement.clientWidth; //计算loading框距离顶部和左部的距离(loading框的宽度为215px,高度为61px) var _Loading

两种数据加载动画

android 数据加载动画: <FrameLayout android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content" > <RelativeLayout android:id="@+id/rl_loading" android:layout_width

MyEclipse10 中的两种FreeMarker插件的安装与配置

freemarker-ideMyEclipce10.0中安装FreeMarker插件,这绝对是最简单的方法.步骤如下:(一)打开http://download.csdn.net/detail/u011883552/8596517下载最新版本,目前本人下载时最新版本是:freemarker-ide-0.9.14(二)将其解压,将hudson.freemarker_ide_0.9.14文件夹放入MyEclipse安装目录dropins下(例:D:\Program Files\MyEclipse10.

深入理解 spring 容器,源码分析加载过程

Spring框架提供了构建Web应用程序的全功能MVC模块,叫Spring MVC,通过Spring Core+Spring MVC即可搭建一套稳定的Java Web项目.本文通过Spring MVC源码分析介绍它的核心实现原理. Tomcat服务器启动入口文件是web.xml,通过在其中配置相关的Listener和Servlet即可加载Spring MVC所需数据.基于Spring MVC最简单的配置如下. <!-- 加载Spring配置文件 --> <context-param>

【死磕 Spring】----- IOC 之 加载 Bean

先看一段熟悉的代码: ClassPathResourceresource new ClassPathResource("bean.xml");DefaultListableBeanFactoryfactory new DefaultListableBeanFactory();XmlBeanDefinitionReaderreader new XmlBeanDefinitionReader(factory);reader.loadBeanDefinitions(resource);这段代

spring IOC之篇六 bean的加载---bean的创建

之前我们讲解了缓存中单例的获取,解下来需要讲解缓存中不存在该如何处理 public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(beanName, "'beanName' must not be null"); // 全局变量需要同步 synchronized (this.singletonObjects) { // 先从单例缓存池获取,以便

Spring学习(一)tomcat加载web.xml、以及项目集成Spring支持

tomcat容器加载web.xml 一. 1 .启动一个 WEB 项目的时候, WEB 容器会去读取它的配置文件 web.xml ,读取 <listener> 和 <context-param> 两个结点. 2 .紧急着,容创建一个 ServletContext ( servlet 上下文),这个 web 项目的所有部分都将共享这个上下文. 3 .容器将 <context-param> 转换为键值对,并交给 servletContext . 4 .容器创建 <li