Home >Java >javaTutorial >How can I inject properties into Spring beans configured with annotations?

How can I inject properties into Spring beans configured with annotations?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 14:39:021017browse

How can I inject properties into Spring beans configured with annotations?

Property Injection into Annotations-Configured Spring Bean

To inject properties into a Spring bean configured using annotations, you can leverage EL support in Spring 3. Consider the following example:

@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {

    @Value("#{systemProperties.databaseName}")
    public void setDatabaseName(String dbName) { ... }
}

In this example, systemProperties is an implicit object that provides access to system properties, allowing you to inject the databaseName property into your PersonDaoImpl bean.

Similarly, you can reference another bean property using EL:

@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }

Where strategyBean is the name of the target bean.

For property injection from a Properties object:

@Value("#{myProperties['github.oauth.clientId']}")
private String githubOauthClientId;

Here, myProperties is a bean that exposes a Properties object. You can directly access properties using EL within a field definition.

The above is the detailed content of How can I inject properties into Spring beans configured with annotations?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn