相关疑难解决方法(0)

Spring 3.1 Environment不适用于用户属性文件

我这样做..

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
xmlReader
        .loadBeanDefinitions(new ClassPathResource("SpringConfig.xml"));
PropertySourcesPlaceholderConfigurer propertyHolder = new PropertySourcesPlaceholderConfigurer();
propertyHolder.setLocation(new ClassPathResource(
        "SpringConfig.properties"));
context.addBeanFactoryPostProcessor(propertyHolder);

    ......

context.refresh();
Run Code Online (Sandbox Code Playgroud)

现在在我的@Configuration文件中,如果我这样做,我的SpringConfig.properties中存在的属性就不会被拾取...

@Autowired
private Environment env
.....
env.getProperty("my.property")
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用,我会获得该属性

@Value("${my.property}")
private String myProperty;
Run Code Online (Sandbox Code Playgroud)

我甚至尝试添加这样的更多行,但没有用.

ConfigurableEnvironment env = new StandardEnvironment();
propertyHolder.setEnvironment(env);
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么我的属性没有加载到Environment中?谢谢.

java spring

17
推荐指数
1
解决办法
2万
查看次数

为什么@Value不能从环境中注入JNDI值?

我在使用@Value注释将Tomcat中的JNDI值注入spring java配置时遇到了麻烦,而我可以通过Environment类检索值.我们使用的是Java 1.7.0_17,Spring 4.0.3和Tomcat 7.0.52.

我在context.xml以下变量中定义了:

<Environment name="USER_NAME" value="initech" type="java.lang.String" />
<Environment name="USER_PASSWORD" value="1n3+3ch!" type="java.lang.String" />
Run Code Online (Sandbox Code Playgroud)

在我的Java配置文件中我有下面的代码工作:

@Bean
public Foo foo( Environment env ){
    return new Foo( env.getProperty("USER_NAME"), env.getProperty("USER_PASSWORD") );
}
Run Code Online (Sandbox Code Playgroud)

当我查看服务器日志时,我看到:

12:50:45.214 [RMI TCP Connection(3)-127.0.0.1] DEBUG o.s.c.e.PropertySourcesPropertyResolver -> Searching for key 'USER_NAME' in [servletConfigInitParams]
12:50:45.214 [RMI TCP Connection(3)-127.0.0.1] DEBUG o.s.c.e.PropertySourcesPropertyResolver -> Searching for key 'USER_NAME' in [servletContextInitParams]
12:50:45.214 [RMI TCP Connection(3)-127.0.0.1] DEBUG o.s.c.e.PropertySourcesPropertyResolver -> Searching for key 'USER_NAME' in [jndiProperties]
12:50:45.214 …
Run Code Online (Sandbox Code Playgroud)

spring tomcat jndi

5
推荐指数
1
解决办法
4130
查看次数

标签 统计

spring ×2

java ×1

jndi ×1

tomcat ×1