欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring實(shí)戰(zhàn)之讓Bean獲取Spring容器操作示例

 更新時(shí)間:2019年11月16日 08:41:24   作者:cakincqm  
這篇文章主要介紹了Spring實(shí)戰(zhàn)之讓Bean獲取Spring容器操作,結(jié)合實(shí)例形式分析了Bean獲取Spring容器的相關(guān)原理、實(shí)現(xiàn)方法及操作注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了Spring實(shí)戰(zhàn)之讓Bean獲取Spring容器操作。分享給大家供大家參考,具體如下:

一 配置

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://www.springframework.org/schema/beans"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
   <!-- 加載容器國際化所需要的語言資源文件 -->
   <bean id="messageSource"
   class="org.springframework.context.support.ResourceBundleMessageSource">
      <property name="basenames">
        <list>
           <value>message</value>
        </list>
      </property>
   </bean>
   <!-- Spring容器會檢測容器中所有Bean,如果發(fā)現(xiàn)某個Bean實(shí)現(xiàn)了
   ApplicationContextAware接口,Spring容器會在創(chuàng)建該Bean之后,
   自動調(diào)用該Bean的setApplicationContext()方法,調(diào)用該方法時(shí),
   會將容器本身作為參數(shù)傳給該方法。-->
   <bean id="person" class="org.crazyit.app.service.Person"/>
</beans>

二 資源文件

hello=\u6b22\u8fce\u4f60\uff0c{0}
now=\u73b0\u5728\u65f6\u95f4\u662f\uff1a{0}

三 Bean

package org.crazyit.app.service;
import org.springframework.context.*;
import org.springframework.beans.BeansException;
import java.util.Locale;
public class Person implements ApplicationContextAware
{
  // 將BeanFactory容器以成員變量保存
  private ApplicationContext ctx;
  /* Spring容器會檢測容器中所有Bean,如果發(fā)現(xiàn)某個Bean實(shí)現(xiàn)了ApplicationContextAware接口,
  Spring容器會在創(chuàng)建該Bean之后,自動調(diào)用該方法,調(diào)用該方法時(shí),
  會將容器本身作為參數(shù)傳給該方法。*/
  public void setApplicationContext(ApplicationContext ctx)
    throws BeansException
  {
    this.ctx = ctx;
  }
  public void sayHi(String name)
  {
    System.out.println(ctx.getMessage("hello" , new String[]{name}
      , Locale.getDefault(Locale.Category.FORMAT)));
  }
}

四 測試類

package lee;
import java.io.*;
import org.springframework.context.*;
import org.springframework.context.support.*;
import org.crazyit.app.service.*;
public class SpringTest
{
  public static void main(String[] args)throws Exception
  {
    ApplicationContext ctx = new
      ClassPathXmlApplicationContext("beans.xml");
    Person p = ctx.getBean("person" , Person.class);
    p.sayHi("孫悟空");
  }
}

五 測試結(jié)果

歡迎你,孫悟空

更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Spring框架入門與進(jìn)階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總

希望本文所述對大家java程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論