spring remark

来源:互联网 发布:双飞姐妹俩体验知乎 编辑:程序博客网 时间:2024/04/30 12:07

工厂类都是简单的,仅提供静态方法和变量的单实例,它们将创建对象,并将这些对象绑定在一起。


package com.openv.spring;


/**
 * 注入HelloWorld和HelloStr依赖性
 *
 * @author luoshifei
 */
public class HelloWorldFactory {
    public static HelloWorld getFileHelloWorld() {
        HelloStr hStr = new FileHelloStr("helloworld.properties");
        HelloWorld hw = new HelloWorld(hStr);

        return hw;
    }
}

package com.openv.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * HelloWorld客户应用
 *
 * @author luoshifei
 */
public class HelloWorldClient {
    protected static final Log log = LogFactory.getLog(HelloWorldClient.class);

    public static void main(String[] args) {
        HelloWorld hw = HelloWorldFactory.getFileHelloWorld();
        log.info(hw.getContent());
    }
}

other:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
   "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

     <bean name="fileHelloWorld"
          class="com.openv.spring.HelloWorld">
          <constructor-arg>
               <ref bean="fileHello"/>
          </constructor-arg>   
     </bean>

     <bean name="fileHello"
          class="com.openv.spring.FileHelloStr">
          <constructor-arg>
               <value>helloworld.properties</value>
          </constructor-arg> 
     </bean>
    
</beans> 

解析配置文件

public class HelloWorldClient {
 protected static final Log log = LogFactory.getLog(HelloWorldClient.class);

 public HelloWorldClient() {
   Resource resource = new ClassPathResource("appcontext.xml");
   BeanFactory factory = new XmlBeanFactory(resource);
   HelloWorld hw = (HelloWorld) factory.getBean("fileHelloWorld");
   log.info(hw.getContent());
 }

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