工厂类都是简单的,仅提供静态方法和变量的单实例,它们将创建对象,并将这些对象绑定在一起。
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();
}
}
本文介绍了一个使用Spring框架进行依赖注入的例子,展示了如何通过工厂类创建并配置依赖关系。具体包括定义依赖项、创建工厂类以及客户端应用程序中使用这些依赖。
1523

被折叠的 条评论
为什么被折叠?



