Webnet Webnet - 4 months ago 23
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

Environment
object.

It works great in my configuration...

@Configuration
@ComponentScan(basePackages = {
"com.production"
})
@PropertySource(value = {
"classpath:/application.properties",
"classpath:/environment-${FETTER_ENVIRONMENT}.properties"
})
@EnableJpaRepositories("com.production.repositories")
@EnableTransactionManagement
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";

@Resource
Environment environment;


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

Is there something special about
Environment
that's preventing this?

@Component
public class Vendor {
private String token;

@Autowired
private Environment environment;

public Vendor() {
//get token from config
//Environment environment = (Environment) ApplicationContextProvider.getApplicationContext().getBean("environment");
setToken(environment.getProperty("api.vendor.token"));
}

public String getToken() {
return token;
}

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


Update: I found this resource which highlights the usage of
@Value
, 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

Answer

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:

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