问题
I'm new to Spring and I'm building an application where some entities (JPA/Hibernate) need access to a property from application.properties. I do have a configuration class in which this is trivial:
@Configuration
public class FactoryBeanAppConfig {
@Value("${aws.accessKeyId}")
private String awsAccessKeyId;
@Value("${aws.secretKey}")
private String awsSecretKey;
}
but since entities do not have and I think they should not have the annotations such as @Configuration
or @Component
, what's the Spring way for them to access the property?
Now, I know I can create my own class, my own bean, and make it as a simple wrapper around the properties; but is that the Spring way to do it or is there another way?
回答1:
specify Property file location using @PropertySource
Something like below
@PropertySource("classpath:/application.proerties")
You also need to add below bean in your config
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
return new PropertySourcesPlaceholderConfigurer();
}
回答2:
There is no "Spring way", since JPA entities and Spring have nothing to do with each other. Most importantly, JPA entities are not Spring beans, so Spring doesn't know or care about them as they're not managed by Spring.
You can try to hack around, trying in vain to access Spring's configuration from code that should not be trying to access it, or you can accept the truth that your design is broken and you're trying to do something that's not meant to be done.
As was proposed several times, use a service class for this. It's managed by Spring, so it can access the Spring config, and it can handle entities, so there's no crossing boundaries.
回答3:
You can use @PropertySource
to load the properties file as follows
@Configuration
@PropertySource("classpath:/com/organization/config/application.proerties")
public class FactoryBeanAppConfig {
...
}
回答4:
Entities should not acces environment properties. If you are using your entity through a service, then the service can access the properties to act on the entity.
来源:https://stackoverflow.com/questions/47221708/whats-the-spring-way-of-accessing-properties-from-an-entity