Injecting Properties into Spring Beans via Annotations
When dealing with Spring beans that are detected via annotations, injecting property values from external sources can be a challenge. This article explores a solution to this problem by utilizing EL support in Spring 3.
The original issue arose due to beans being annotated with @Repository, eliminating the option of explicitly configuring them in the Spring XML file. However, to inject a property value, a typical approach using the bean's XML configuration would not be feasible.
The solution lies in leveraging the @Value annotation in Spring 3, which allows developers to inject property values directly into fields or setter methods. The syntax for this is:
@Value("#{systemProperties.databaseName}") public void setDatabaseName(String dbName) { ... }
The systemProperties object is an implicit object, and the databaseName property can be accessed within the setter method.
Furthermore, it is possible to inject properties from Properties objects using @Value:
@Value("#{myProperties['github.oauth.clientId']}") private String githubOauthClientId;
This method provides a flexible way to inject external property values into Spring beans. For more detailed information, refer to the blog post provided in the original answer.
The above is the detailed content of How to Inject Properties into Spring Beans Annotated with @Repository?. For more information, please follow other related articles on the PHP Chinese website!