Mule ESB在Callable类之外读取@Value属性

时间:2018-03-09 12:39:57

标签: java spring mule mule-esb

如何阅读 @Value 属性在MuleESB上实现Callable接口的类?就我而言, some_property

  • 在MainClass(ok)
  • 中的onCall方法中不为null
  • 在ClassB中的foo()methid(错误)
  • 时为null

如何在foo()方法中获取此值?我不想将其作为参数传递。

public class MainClass implements Callable {

    @Value("${some_property}")
    String some_property;

    @Override
    public Object onCall(MuleEventContext eventContext) throws Exception {      
        System.out.println(some_property); //some_property is ok
        ClassB obB = new ClassB();
        obB.foo();// some_property inside this method is null
    }
}

public ClassB {
    @Value("${some_property}")
    String some_property;

    public void foo() {
        System.out.println(some_property); 
    }
}

编辑:有关我的问题的更多信息

我的MuleESB项目包含位于以下文件中的资源文件:
/MY_PROJECT/src/main/resources/services.properties 它包含一些值,如

some_property = AAAA
another_property = BBBB

我的flow.xml文件中的一个文件被引用:
/MY_PROJECT/src/main/app/common.xml

<context:property-placeholder location="classpath:services.properties"
        order="4" ignore-unresolvable="true" />

我想在另一个流程中使用此配置。我在Java组件中有一个实现Callable接口的类

public class MainClass implements Callable {

    @Value("${some_property}")
    String some_property;

    @Override
    public Object onCall(MuleEventContext eventContext) throws Exception {      
        System.out.println(some_property); //some_property is ok
        ClassB obB = new ClassB();
        obB.foo();// some_property inside this method is null
    }
}

我有经常使用的第二类ClassB。我想在MainClass

之前提到的onCall()方法中运行它
public ClassB {
    @Value("${some_property}")
    String some_property;

    public void foo() {
        System.out.println(some_property); 
    }
}

我想从services.properties文件中加载some_property值。我使用以下代码

    @Value("${some_property}")
    String some_property;

我想仅在ClassB foo()方法中读取此值。但是现在有空(而不是设置值的MainClass onCall()方法)。 ClassB是独立的,可以在几个onCall()方法中使用,所以我不想在MainClass中读取这些属性并将它们传递给ClassB构造函数或方法。我怎么能做到这一点?

2 个答案:

答案 0 :(得分:1)

我只是使用构造函数来读取props文件。如果要创建许多ClassB对象,可能需要更改此文件一次,而不是每个新实例。

public ClassB {

    String some_property;

    public ClassB() {

        Properties p = new Properties();
        try {
            p.load( this.getClass().getResourceAsStream("your-props-file.properties") );
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        some_property = p.getProperty("some_property");
    }

    public void foo() {
        System.out.println(some_property); 
    }
}

答案 1 :(得分:0)

请使用方法注入尝试此操作,现在可以在外面调用MainClass.some_property。

public static String some_property;

@Value("${some_property}")
public void setSome_property(String prop) {
    some_property = prop;
}