spring静态工厂实例化

来源:互联网 发布:microsoft fix it卸载 编辑:程序博客网 时间:2024/05/01 14:50

搭建环境同上

    

1---在src/resource下加入-----applicationContext-web.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"        "http://www.springframework.org/dtd/spring-beans-2.0.dtd"><beans><!--静态工厂实例化--><bean id="beanFactory" class="com.neusoft.test.spring.factory.BeanFactory" factory-method="createFormat" /></beans>


 

2---在src/java下加入

      四个包  factory   format    impl   main

      1------- 在factory中加入  -----BeanFactory.java    

package com.neusoft.test.spring.factory;import com.neusoft.test.spring.format.Format;import com.neusoft.test.spring.format.impl.LowerFormat;public class BeanFactory {public static  Format createFormat(){return new LowerFormat();}}

    2------- 在format  中加入  -----Format.java    

package com.neusoft.test.spring.format;public interface Format { String format(String text);}

    3------- 在impl中加入  -----LowerFormat.java    

package com.neusoft.test.spring.format.impl;import com.neusoft.test.spring.format.Format;public class LowerFormat implements Format {public String format(String text) {return text.toLowerCase();}}

    4------- 在main中加入  -----Test.java      

package com.neusoft.test.spring.main;import com.neusoft.test.spring.format.impl.LowerFormat;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {public static void main(String[] args) {//静态工厂实例化ApplicationContext applicationContext=new ClassPathXmlApplicationContext(new String("applicationContext-web.xml"));LowerFormat lowerFormat=(LowerFormat)applicationContext.getBean("beanFactory");System.out.println(lowerFormat.format("abcABC"));}}


     

原创粉丝点击