简体   繁体   中英

Java Spring Injection String

How do I inject a String into a class. I Have seen plenty of examples of how to inject a class but can't find any for a String.

An example: If your field is called "name" and your class is called "Person" you can use setter injection like this:

<bean id="personBean" class="example.Person">
    <property name="name" value="Paul" />
</bean>

It should be as simple as that. You will obviously need setter methods in your Person class for name.

Let Spring know where to find your properties file (in this case myProperties.properties):

    <!-- Spring will replace ${} keys with values from the file used by the propertyConfigurer   -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="location" value="classpath:myProperties.properties"/>
    </bean>

In your class, you can inject like this:

@Value("${web.theme}")
private String theme;

In this case, the property defined bye "web.theme" in myProperties.properties will be injected into the "theme" member variable. But you can also inject in the constructor or setter as well.

If you don't want to use annotations, you can use it in your xml file as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM