简体   繁体   English

使用 XML 中的参数实例化 Java Spring Bean

[英]Instantiating a Java Spring Bean with parameters in XML

I have two packages A and B with a class X within package B. I need to use an instance of a X in A.我有两个包 A 和 B,包 B 中有一个类 X。我需要在 A 中使用 X 的实例。

Catch here is package B contains Java Bean spring configuration while A uses XML.这里要注意的是包 B 包含 Java Bean spring 配置,而 A 使用 XML。

Here is how package B's AppConfig looks like.下面是包 B 的 AppConfig 的样子。

@Configuration
public class PackageBJavaBeans {

 @Bean
 public X getX(final String paramOne, final String paramTwo) {
    String value = doSomeProcessingWithParameters(paramOne, paramTwo);
    return new X(value);
 }

 private String getXValue(final String paramOne, final String paramTwo){
   final String value = //do-some-calculation
   return value;
 } 

}

I need to create a bean of class X in package "A" with XML.我需要用 XML 在包“A”中创建一个 X 类的 bean。 How do I pass parameters via XML from package A?如何通过包 A 中的 XML 传递参数?

Thanks.谢谢。

I think this is what you're asking for.我想这就是你要问的。

<?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">

   <!-- Definition for X bean -->
   <bean id="X" class="A.X">
      <constructor-arg value="The value this bean holds"/>
   </bean>

</beans>

I'm a little confused on what exactly you want.我对你到底想要什么有点困惑。 Do you still want us to use the provided function that would concatenate the two strings together before creating X?您是否仍然希望我们使用提供的函数在创建 X 之前将两个字符串连接在一起? That is possible using a factory method.使用工厂方法可以做到这一点。 Let me know if you want an example of a factory method bean.如果您想要工厂方法 bean 的示例,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM