10

I have one utility class where i have one method which requires username and password to connect other url. I need to kept that username in properties file so that i can change it any time. But as i am using it in static method (being utility class) , Issue is it is showing null .(i.e. it is not able to read from properties file).

But when i ckecked that values in some other controller they are getting there. So my question is how to read property value in static field

<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath*:/myservice_detaults.properties</value>
            <value>classpath*:/log4j.properties</value>
        </list>
    </property>
</bean>

//in Utitlity class code

  @Value("${app.username}")
      static String userName;

public static connectToUrl(){
  //use userName
 //userName showing null
}
user3608352
  • 397
  • 2
  • 5
  • 15
  • How is your utility class loaded/injected ? – superbob Jul 09 '14 at 08:51
  • My utility class is normal class not spring class and calling connectToUrl as normal static calling – user3608352 Jul 09 '14 at 09:01
  • If your utility class is not loaded by the spring context, you cannot inject parameters in it. However you can still use the solution proposed by @AmitChotaliya. A good practice with Spring is to use singleton beans loaded by the spring context instead of static methods in utility classes. – superbob Jul 09 '14 at 09:19
  • 1
    @superbob thanks i guess solution provided by AmitChotaliya should work with my issue.Ill try. But can you bit explain about your point >> "A good practice with Spring is to use singleton beans loaded by the spring context instead of static methods in utility classes.".. any link for more info – user3608352 Jul 09 '14 at 10:43
  • There are a lot of reason for this, but at least, you would have your `@Value("${app.username}")` property initialized properly without doing anything special. If you want some links, the 2nd answer to this question can give you some more "arguments" http://stackoverflow.com/questions/7270681/utility-class-in-spring-application-should-i-use-static-methods-or-not#7270779. Base on my own experience, I use static methods on utility class only if I don't need initialization to use them (which is not your case). Otherwise, I use spring beans. – superbob Jul 09 '14 at 11:07

6 Answers6

13

In you Utility class you can have a setter method to set the properties and then you can use MethdInvokingFactoryBean.

class Utility{
    static String username;
    static String password;
    public static setUserNameAndPassword(String username, String password){
        Utility.username = username;
        Utility.password = password;
    }
    //other stuff
}

<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath*:/myservice_detaults.properties</value>
            <value>classpath*:/log4j.properties</value>
        </list>
    </property>
</bean>

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Utility.setUserNameAndPassword"/>
    <property name="arguments">
        <list>
            <value>${username}</value>
            <value>${password}</value>
        </list>
   </property>
</bean>
bitkot
  • 4,466
  • 2
  • 28
  • 39
10

Or using the @Value over the non-static setter method for username eg.

@Value("${app.username}")
public void setUserName(String userName) {
    UtilityClass.userName = userName;
}
CuE
  • 361
  • 3
  • 9
5
Read property value from properties file in static field of class using Java based spring configuration.
Example :
// The property file to store fields.
user.properties
     username=Elijah Wood
     age=26
     language=English
// This class holds the static values

package org.javahive.propertyreader.example;

public class UserDetails {

    static String username;
    static String age;
    static String language;

    public static void setUserValues(String username, String age, String language) {
        UserDetails.username = username;
        UserDetails.age = age;
        UserDetails.language = language;
    }
}

//Spring configuration class

package org.javahive.propertyreader.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan(value = { "org.javahive.propertyreader.example" })
@PropertySource("classpath:user.properties")
public class PropertyReaderConfig {

    @Value("${user}")
    private String username;

    @Value("${age}")
    private String age;

    @Value("${language}")
    private String language;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public MethodInvokingFactoryBean methodInvokingFactoryBean() {
        MethodInvokingFactoryBean mifb = new MethodInvokingFactoryBean();
        mifb.setStaticMethod("org.javahive.propertyreader.example.UserDetails.setUserValues");
        mifb.setArguments(new String[] { this.username, this.age, this.language });
        return mifb;
    }

    /**
     * @return the name
     */
    public String getName() {
        return username;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.username = name;
    }

    /**
     * @return the age
     */
    public String getAge() {
        return age;
    }

    /**
     * @param age
     *            the age to set
     */
    public void setAge(String age) {
        this.age = age;
    }

    /**
     * @return the language
     */
    public String getLanguage() {
        return language;
    }

    /**
     * @param language
     *            the language to set
     */
    public void setLanguage(String language) {
        this.language = language;
    }

}

//The main class.

package org.javahive.propertyreader.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(PropertyReaderConfig.class);
        System.out.println("User Name : " + UserDetails.username);
        System.out.println("Age : " + UserDetails.age);
        System.out.println("Language : " + UserDetails.language);
    }
}
Rajesh
  • 4,273
  • 1
  • 32
  • 33
5

Try this : Make your class a Component

@Component
public class UserXXXUtils {
    private static Integer trustXXXMask;

    @Value("${trustXXXMask}")
    public void setTrustXXXMask(Integer trustXXXMask) {
        UserXXXUtils.trustXXXMask = trustXXXMask;
    }
    //Access anywhere in the class
}
0

Spring doesn't allow to inject values into non-final static fields but make your field private and it should works.

Bananan
  • 613
  • 5
  • 19
0

Or just

<bean id="constants" class="com.foo.constants.CommonConstants">
    <property name="username" value="${username}"/>
</bean>
zhuguowei
  • 8,401
  • 16
  • 70
  • 106