Webnet Webnet - 5 months ago 26
Java Question

How to autowire a Spring Environment object

I'm attempting to get properties from a .properties file within an object of my application. My only knowledge of how to do this is via the


It works great in my configuration...

@ComponentScan(basePackages = {
@PropertySource(value = {
public class Config {
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USER = "db.user";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";

private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";

Environment environment;

But I try to do it in another class and it's null. I've tried using
and manual injection.

Is there something special about
that's preventing this?

public class Vendor {
private String token;

private Environment environment;

public Vendor() {
//get token from config
//Environment environment = (Environment) ApplicationContextProvider.getApplicationContext().getBean("environment");

public String getToken() {
return token;

public void setToken(String token) {
this.token = token;

Update: I found this resource which highlights the usage of
, but I don't use any XML configuration in my application.

It looks like this might be what I'm looking for: Loading properties in Spring 3.1 programmatically


You need to use @Value annotaion for it. But before it is required to declare <context:property-placeholder in xml.

See here for details.

Also, another way:

ApplicationContext context;
Enviroment env = context.getEnvironment();