Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/403.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaSpring:覆盖占位符行为以返回';foo';_Java_Spring - Fatal编程技术网

JavaSpring:覆盖占位符行为以返回';foo';

JavaSpring:覆盖占位符行为以返回';foo';,java,spring,Java,Spring,使用JavaSpring时,如何覆盖属性占位符的默认行为以返回任何属性的“foo” 我现在要做的是扩展PropertySource,如下所示: public class FooPropertySource extends PropertySource<Object> { private static final String DEFAULT_NAME = "foo"; public FooPropertySource() { super(DEFAUL

使用JavaSpring时,如何覆盖属性占位符的默认行为以返回任何属性的“foo”

我现在要做的是扩展PropertySource,如下所示:

public class FooPropertySource extends PropertySource<Object> {
    private static final String DEFAULT_NAME = "foo";

    public FooPropertySource() {
        super(DEFAULT_NAME, null);
    }

    @Override
    public Object getProperty(String name) {
        return "foo";
    }
}
公共类FooPropertySource扩展了PropertySource{
私有静态最终字符串DEFAULT_NAME=“foo”;
公共FoodPropertySource(){
超级(默认名称,空);
}
@凌驾
公共对象getProperty(字符串名称){
返回“foo”;
}
}
在这一点上,我有两个问题:

A) 如何处理应用程序上下文XML文件?到目前为止,我已经将其定义为一个bean…仅此而已

B) 我是否需要在代码中执行任何操作来从我的应用程序上下文加载其他bean,以便它们使用FooPropertySource


谢谢

您必须注册此PropertySource才能添加到应用程序上下文中。如果手动启动应用程序上下文,则可以执行以下操作:

    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
    ctx.setConfigLocation("applicationContext.xml");
    ctx.getEnvironment().getPropertySources().addLast(new FooPropertySource());
    ctx.refresh();
如果您在web环境中执行此操作,则必须注册一个自定义项以拦截应用程序上下文,然后才能刷新该应用程序上下文以注入到您的PropertySource中:

public class CustomInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
    public void initialize(ConfigurableWebApplicationContext ctx) {
        ctx.getEnvironment().getPropertySources().addLast(new FooPropertySource());
    }
}
公共类CustomInitializer实现ApplicationContextInitializer{
公共无效初始化(ConfigurableWebApplicationContext ctx){
ctx.getEnvironment().getPropertySources().addLast(新的FoopPropertySource());
}
}

更多细节

我最终选择了另一个方向(通过扩展PropertyPlaceHolderConfigure),但您的答案似乎是正确的。但是,这个实现对我来说不起作用,因为我使用的上下文实例不返回ConfigurableEnvironment(因此我无法对其调用getEnvironment()。谢谢你的帮助:)