想要在Spring-Common.xml中引用 Spring-Output.xml中定义的bean 需要使用<ref bean="XXX"/>
标签,如果是同一个xml文件中引用则使用<ref local="XXX"/>
标签。
package com.spring.output;
public class OutputHelper {
IOutputGenerator outputGenerator;
public void generateOutput(){
this.outputGenerator.generateOutput();
}
public void setOutputGenerator(IOutputGenerator outputGenerator){
this.outputGenerator = outputGenerator;
}
}
Spring-Output.xml
<?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-3.0.xsd">
<bean id="CsvOutputGenerator" class="com.spring.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.spring.output.impl.JsonOutputGenerator" />
</beans>
Spring-Common.xml
<?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-2.5.xsd">
<bean id="OutputHelper" class="com.spring.output.OutputHelper">
<property name="outputGenerator" >
<ref bean="CsvOutputGenerator"/>
</property>
</bean>
</beans>
在调用的上下文方法的时候这样写:
package com.spring.hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.output.OutputHelper;
public class App {
private static ApplicationContext context;
public static void main(String[] args)
{
context = new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml","Spring-Output.xml"});
OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
output.generateOutput();
}
}
CsvOutputGenerator.java
package com.spring.output.impl;
import com.spring.output.IOutputGenerator;
public class CsvOutputGenerator implements IOutputGenerator {
public void generateOutput() {
System.out.println("Creating CsvOutputGenerator Output......");
}
}
JsonOutputGenerator.java
package com.spring.output.impl;
import com.spring.output.IOutputGenerator;
public class JsonOutputGenerator implements IOutputGenerator {
public void generateOutput() {
System.out.println("Creating JsonOutputGenerator output.......");
}
}
IOutputGenerator.java
package com.spring.output;
public interface IOutputGenerator {
public void generateOutput();
}
时间: 2024-09-23 20:50:13